コード例 #1
0
ファイル: main.c プロジェクト: yogpstop/MyGCCProj
int main(int argc, char **argv) {
	if (argc != 2) return 1;
	DWORD pid = strtoul(argv[1], NULL, 10);
	char *path = malloc(MAX_PATH);
	GetModuleFileNameA(NULL, path, MAX_PATH);
	*strrchr(path, '\\') = 0;
	HANDLE proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
	BOOL w32;
#if defined(_WIN64)
	IsWow64Process(proc, &w32);
#elif defined(_WIN32)
	w32 = TRUE;
#endif
	CloseHandle(proc);
	const char *bit = w32 ? "32" : "64";
	char *full = malloc((strlen(path) + 11) * 2 + 17);
	sprintf(full, "\"%s\\hook%s.exe\" \"%s\\hook%s.dll\" %I32u", path, bit, path, bit, pid);
	STARTUPINFO si = {};
	si.cb = sizeof(STARTUPINFO);
	PROCESS_INFORMATION pi = {};
	CreateProcess(NULL, full, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
	CloseHandle(pi.hThread);
	WaitForSingleObject(pi.hProcess, INFINITE);
	CloseHandle(pi.hProcess);
	free(full);
	free(path);
	HANDLE mutex[BUF_SIZE], event;
	char tmp[32], *cptr;
	sprintf(tmp, "GLC_SM_%I32u_", pid);
	cptr = tmp + strlen(tmp);
	strcpy(cptr, "EVENT");
	event = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, tmp);
	strcpy(cptr, "MUTEX0");
	mutex[0] = OpenMutex(SYNCHRONIZE, FALSE, tmp);
	strcpy(cptr, "MUTEX1");
	mutex[1] = OpenMutex(SYNCHRONIZE, FALSE, tmp);
	strcpy(cptr, "MUTEX2");
	mutex[2] = OpenMutex(SYNCHRONIZE, FALSE, tmp);
	strcpy(cptr, "FILE");
	HANDLE fm = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, tmp);
	void *fm_buf = MapViewOfFile(fm, FILE_MAP_ALL_ACCESS, 0, 0, 0);
	vfw_str *vfwctx = vfw_init();
	int i;
	DBG_PERF_INIT(3, 8, GLC_FPS * 60 * 60);
	while (WaitForSingleObject(event, 5000) == WAIT_OBJECT_0) {
		DBG_PERF(3, 0);
		i = *((uint8_t*)fm_buf + GLC_MAX_SIZE * BUF_SIZE);
		DBG_PERF(3, 1);
		WaitForSingleObject(mutex[i], INFINITE);
		DBG_PERF(3, 2);
		ResetEvent(event);
		DBG_PERF(3, 3);
		vfw_frame(vfwctx, fm_buf + GLC_MAX_SIZE * i);
		DBG_PERF(3, 6);
		ReleaseMutex(mutex[i]);
		DBG_PERF(3, 7);
		DBG_PERF_INC(3);
	}
	DBG_PERF_FLUSH();
	vfw_end(vfwctx);
	UnmapViewOfFile(fm_buf);
	CloseHandle(fm);
	CloseHandle(mutex[2]);
	CloseHandle(mutex[1]);
	CloseHandle(mutex[0]);
	CloseHandle(event);
	return 0;
}
コード例 #2
0
ファイル: link_vti.c プロジェクト: Jonimoose/tilp-libticables
static int vti_open(CableHandle *h)
{
	int i;
	char vLinkFileName[32];
	char name[32];
	HANDLE hVLinkFileMap = NULL;
	HANDLE Handle;
	ATOM a;

	/* Get an handle on the VTi window */
	otherWnd = FindWindow("TEmuWnd", NULL);
	if (!otherWnd)
		return ERR_VTI_FINDWINDOW;

	/* Get the current DLL handle */
	Handle = GetModuleHandle("libticables2.dll");
	if(!Handle)
		Handle = GetModuleHandle("libticables2-5.dll");

	if (!Handle)
	{
		ticables_critical(_("FATAL ERROR: unable to get an handle on the ticables-2 library."));
		ticables_critical(_("Did you rename the library ?!"));
		return ERR_NO_LIBRARY;
	}

	/* Create a file mapping handle for the 'lib->VTi' communication channel */
	for (i = 0; ; i++)
	{
		sprintf(vLinkFileName, "Virtual Link %d", i);
		hVLinkFileMap = CreateFileMapping((HANDLE) - 1, NULL,
				      PAGE_READWRITE, 0,
				      sizeof(LinkBuffer), vLinkFileName);
  
		if (GetLastError() != ERROR_ALREADY_EXISTS)
			break;
	}

	ticables_info("Virtual Link L->V %i", i);
	vSendBuf = (LinkBuffer *)MapViewOfFile(hVLinkFileMap, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(LinkBuffer));

	// Inform VTI of our virtual link so that it can enable it. It should return
	// its virtual link name in a message.
	SendMessage(otherWnd, WM_HELLO, 0, (LPARAM) Handle);
  
	/* Retrieve the VTi virtual link name */
	//b = GetMessage(&msg, NULL, WM_HELLO, WM_SEND_BUFFER);
	//WaitMessage();                                                                                // Waits VTi answer

	/* Create a file mapping handle for the 'Vti->lib' communication channel */
	ticables_info("Virtual Link V->L %i", i-1);
	sprintf(name, "Virtual Link %d", i - 1);
	hMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name);
	if (hMap)
	{
		ticables_info(_("Opened %s"), name);
		vRecvBuf = (LinkBuffer *)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(LinkBuffer));
	}
	else
		return ERR_VTI_OPENFILEMAPPING;

	/* Send to VTi the name of our virtual link. VTi should open it (lib -> Vti) */
	a = GlobalAddAtom(vLinkFileName);
	SendMessage(otherWnd, WM_SEND_BUFFER, 0, (LPARAM) a);
	GlobalDeleteAtom(a);

	/* Enable linking (check the VTi's Virtual Link|Enable cable link' item) */
	if (otherWnd)
		SendMessage(otherWnd, WM_ENABLE_LINK, 0, 0);

	vSendBuf->start = vSendBuf->end = 0;
	vRecvBuf->start = vRecvBuf->end = 0;

	return 0;
}
コード例 #3
0
bool CanalSharedMemLevel1::doCmdOpen( const char *szInterface, unsigned long flags )
{
    HANDLE hMapListen = NULL;
    HANDLE hListenMutex = NULL;
    HANDLE semListenCommand = NULL;
    HANDLE semListenDone = NULL;
    DWORD err;

    bool rv = true;	// return value
    wxChar buf[ MAX_PATH ];
    struct __shmOpen *pListenShMemArea = NULL;


    ::wxLogDebug( _T("CanalSharedMemLevel1: Before %ul"), GetLastError() );
    SetLastError( 0 );


    if ( NULL == ( semListenCommand =
                       OpenSemaphore( SEMAPHORE_ALL_ACCESS,
                                      FALSE,
                                      CANAL_LISTEN_COMMAND_SEM ) ) ) {

        ::wxLogDebug( _T("CanalSharedMemLevel1: Failed to open Listen Command semaphore %ul"),
                      ( err = GetLastError() ) );
        return false;
    }


    if ( NULL == ( semListenDone =
                       OpenSemaphore( SEMAPHORE_ALL_ACCESS,
                                      FALSE,
                                      CANAL_LISTEN_DONE_SEM ) ) ) {

        ::wxLogDebug( _T("CanalSharedMemLevel1: Failed to open Listen Done semaphore %ul"),
                      ( err = GetLastError() ) );
        CloseHandle( semListenCommand );
        return false;
    }

    // Get client shared memory
    if ( NULL == ( hMapListen =
                       OpenFileMapping( FILE_MAP_WRITE,
                                        TRUE,
                                        CANAL_LISTEN_SHM_NAME ) ) ) {

        ::wxLogDebug( _T("CanalSharedMemLevel1: Failed to open Listen Command semaphore %ul"),
                      ( err = GetLastError() ) );
        CloseHandle( semListenCommand );
        CloseHandle( semListenDone );
        return false;
    }

    if ( NULL == ( pListenShMemArea =
                       (struct __shmOpen *)MapViewOfFile( hMapListen,
                               FILE_MAP_WRITE, 0, 0, 0 ) ) ) {

        ::wxLogDebug( _T("CanalSharedMemLevel1: Failed to open Listen Shared memory %ul"),
                      ( err = GetLastError() ) );
        CloseHandle( hMapListen );
        CloseHandle( semListenCommand );
        CloseHandle( semListenDone );
        return false;
    }

    if ( NULL == ( hListenMutex =
                       OpenMutex( MUTEX_ALL_ACCESS,
                                  TRUE,
                                  CANAL_LISTEN_SHARED_MEMORY_MUTEX ) ) ) {

        ::wxLogDebug( _T("CanalSharedMemLevel1: Failed to open Listen Nutex %ul"),
                      GetLastError() );
        UnmapViewOfFile( pListenShMemArea );
        CloseHandle( hMapListen );
        CloseHandle( semListenCommand );
        CloseHandle( semListenDone );
        return false;
    }

    // Get access to Listenthread common resources
    WaitForSingleObject( hListenMutex, INFINITE );

    // Write Command
    pListenShMemArea->m_command = CANAL_COMMAND_OPEN_VSCP_LEVEL1;
    pListenShMemArea->m_flags = flags;
    if ( NULL != szInterface ) {
        strncpy( pListenShMemArea->m_strIfName, szInterface, sizeof( szInterface ) );
    }

    // Execute command on server
    ReleaseSemaphore( semListenCommand, 1, NULL );

    // Wait until command is handled
    WaitForSingleObject( semListenDone, INFINITE );

    if ( !pListenShMemArea->m_cmdResult ) {

        // Give the server thread some time to start
        Sleep( 1 );

        // Get the client command memory area
        _stprintf( buf, CANAL_LISTEN_CLIENT_SHM_TEMPLATE, pListenShMemArea->m_shmid );
        if ( NULL != ( m_hMapClient =
                           OpenFileMapping( FILE_MAP_WRITE, TRUE, buf ) ) ) {

            if ( NULL != ( m_pCommandMem = MapViewOfFile( m_hMapClient,
                                           FILE_MAP_WRITE, 0, 0, 0 ) ) ) {

                // Save a pointer to the command structure
                m_pLevel1 = (struct __shmCanalLevelI *)m_pCommandMem;

                // Wait for server thread to give clearence
                DWORD start = GetTickCount();
                while( 0xaa55 != m_pLevel1->m_test ) {
                    if ( ( GetTickCount() - start ) > 1000 ) {

                        // Release listen thread resources we are done with them

                        // No need for memory anymore
#ifndef CANAL_MFCAPP
                        wxLogDebug(_T("ERROR: No server thread\n"));
#endif
                        return false;
                    }
                }

                // Get the Client Semaphores
                _stprintf( buf, CANAL_CLIENT_COMMAND_SEM_TEMPLATE, pListenShMemArea->m_shmid );
                if ( NULL == ( m_semClientCommand = OpenSemaphore( SEMAPHORE_ALL_ACCESS,
                                                    TRUE,
                                                    buf ) ) ) {
                    CloseHandle( semListenCommand );
                    return false;
                }

                _stprintf( buf, CANAL_CLIENT_DONE_SEM_TEMPLATE, pListenShMemArea->m_shmid );
                if ( NULL == ( m_semClientDone = OpenSemaphore( SEMAPHORE_ALL_ACCESS,
                                                 TRUE,
                                                 buf ) ) ) {
                    CloseHandle( semListenCommand );
                    return false;
                }

                // Go on
                m_pLevel1->m_test = 0x55aa;

                // We have an open channel!
                // Do a dummy Open of interface
                doCommand( CANAL_COMMAND_OPEN );

            }
            else {

                // Failed to map in client shared memory

            }

        }
        else {

            // Failed to get Client shared memory

        }

    }

    // Release listen thread resources we are done with them
    ReleaseMutex( hListenMutex );

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

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

    // release listthread sh memory
    if ( NULL != pListenShMemArea ) {
        UnmapViewOfFile( pListenShMemArea );
    }

    // ...and handle for shared memory
    if ( NULL != hMapListen ) {
        CloseHandle( hMapListen );
    }

    return rv;
}
コード例 #4
0
ファイル: THAllocator.c プロジェクト: Northrend/pytorch
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;
}
コード例 #5
0
ファイル: RTSS_Timer.cpp プロジェクト: hogepiyosan/RTSS_Timer
BOOL UpdateOSD(LPCSTR lpText)
{
	BOOL bResult	= FALSE;

	HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, TEXT("RTSSSharedMemoryV2"));

	if (hMapFile)
	{
		LPVOID pMapAddr				= MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
		LPRTSS_SHARED_MEMORY pMem	= (LPRTSS_SHARED_MEMORY)pMapAddr;

		if (pMem)
		{
			if ((pMem->dwSignature == 'RTSS') && 
				(pMem->dwVersion >= 0x00020000))
			{
				for (DWORD dwPass=0; dwPass<2; dwPass++)
					//1st pass : find previously captured OSD slot
					//2nd pass : otherwise find the first unused OSD slot and capture it
				{
					for (DWORD dwEntry=1; dwEntry<pMem->dwOSDArrSize; dwEntry++)
						//allow primary OSD clients (i.e. EVGA Precision / MSI Afterburner) to use the first slot exclusively, so third party
						//applications start scanning the slots from the second one
					{
						RTSS_SHARED_MEMORY::LPRTSS_SHARED_MEMORY_OSD_ENTRY pEntry = (RTSS_SHARED_MEMORY::LPRTSS_SHARED_MEMORY_OSD_ENTRY)((LPBYTE)pMem + pMem->dwOSDArrOffset + dwEntry * pMem->dwOSDEntrySize);

						if (dwPass)
						{
							if (!lstrlen(pEntry->szOSDOwner))
								lstrcpy(pEntry->szOSDOwner, UniqueMapName);
						}

						if (!lstrcmp(pEntry->szOSDOwner, UniqueMapName))
						{
							if (pMem->dwVersion >= 0x00020007)
								//use extended text slot for v2.7 and higher shared memory, it allows displaying 4096 symbols
								//instead of 256 for regular text slot
								lstrcpyn(pEntry->szOSDEx, lpText, sizeof(pEntry->szOSDEx) - 1);
							else
								lstrcpyn(pEntry->szOSD, lpText, sizeof(pEntry->szOSD) - 1);

							pMem->dwOSDFrame++;

							bResult = TRUE;

							break;
						}
					}

					if (bResult)
						break;
				}
			}

			UnmapViewOfFile(pMapAddr);
		}

		CloseHandle(hMapFile);
	}

	return bResult;
}
コード例 #6
0
my_bool pvio_shm_connect(MARIADB_PVIO *pvio, MA_PVIO_CINFO *cinfo)
{
  const char *base_memory_name;
  char *prefixes[]= {"", "Global\\", NULL};
  char *shm_name, *shm_suffix, *shm_prefix;
  uchar i= 0;
  int len;
  int cid;
  DWORD dwDesiredAccess= EVENT_MODIFY_STATE | SYNCHRONIZE;
  HANDLE hdlConnectRequest= NULL,
         hdlConnectRequestAnswer= NULL,
         file_map= NULL;
  LPVOID map= NULL;
  PVIO_SHM *pvio_shm= (PVIO_SHM*)LocalAlloc(LMEM_ZEROINIT, sizeof(PVIO_SHM)); 

  if (!pvio_shm)
  {
    PVIO_SET_ERROR(cinfo->mysql, CR_OUT_OF_MEMORY, "HY000", 0, "");
    return 0;
  }

  /* MariaDB server constructs the event name as follows:
     "Global\\base_memory_name" or
     "\\base_memory_name"
   */
 

  base_memory_name= (cinfo->host) ? cinfo->host : SHM_DEFAULT_NAME;

  if (!(shm_name= (char *)LocalAlloc(LMEM_ZEROINIT, strlen(base_memory_name) + 40)))
  {
    PVIO_SET_ERROR(cinfo->mysql, CR_OUT_OF_MEMORY, "HY000", 0, "");
    goto error;
  }

  /* iterate through prefixes */
  while (prefixes[i])
  {
    len= sprintf(shm_name, "%s%s_", prefixes[i], base_memory_name);
    shm_suffix= shm_name + len;
    strcpy(shm_suffix, "CONNECT_REQUEST");
    if ((hdlConnectRequest= OpenEvent(dwDesiredAccess, 0, shm_name)))
    {
      /* save prefix to prevent further loop */
      shm_prefix= prefixes[i];
      break;
    }
    i++;
  }
  if (!hdlConnectRequest)
  {
    PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "Opening CONNECT_REQUEST event failed", GetLastError());
    goto error;
  }

  strcpy(shm_suffix, "CONNECT_ANSWER");
  if (!(hdlConnectRequestAnswer= OpenEvent(dwDesiredAccess, 0, shm_name)))
  {
    PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "Opening CONNECT_ANSWER event failed", GetLastError());
    goto error;
  }
  
  /* get connection id, so we can build the filename used for connection */
  strcpy(shm_suffix, "CONNECT_DATA");
  if (!(file_map= OpenFileMapping(FILE_MAP_WRITE, 0, shm_name)))
  {
    PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "OpenFileMapping failed", GetLastError());
    goto error;
  }

  /* try to get first 4 bytes, which represents connection_id */
  if (!(map= MapViewOfFile(file_map, FILE_MAP_WRITE, 0, 0, sizeof(cid))))
  {
    PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "Reading connection_id failed", GetLastError());
    goto error;
  }

  /* notify server */
  if (!SetEvent(hdlConnectRequest))
  {
    PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "Failed sending connection request", GetLastError());
    goto error;
  }

  /* Wait for server answer */
  switch(WaitForSingleObject(hdlConnectRequestAnswer, pvio->timeout[PVIO_CONNECT_TIMEOUT])) {
  case WAIT_ABANDONED:
    PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "Mutex was not released in time", GetLastError());
    goto error;
    break;
  case WAIT_FAILED:
    PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "Operation wait failed", GetLastError());
    goto error;
    break;
  case WAIT_TIMEOUT:
    PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "Operation timed out", GetLastError());
    goto error;
    break;
  case WAIT_OBJECT_0:
    break;
  default:
    PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "Wait for server failed", GetLastError());
    break;
  }

  cid= uint4korr(map);

  len= sprintf(shm_name, "%s%s_%d_", shm_prefix, base_memory_name, cid);
  shm_suffix= shm_name + len;
  
  strcpy(shm_suffix, "DATA");
  pvio_shm->file_map= OpenFileMapping(FILE_MAP_WRITE, 0, shm_name);
  if (pvio_shm->file_map == NULL)
  {
    PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "OpenFileMapping failed", GetLastError());
    goto error;
  }
  if (!(pvio_shm->map= MapViewOfFile(pvio_shm->file_map, FILE_MAP_WRITE, 0, 0, PVIO_SHM_BUFFER_SIZE)))
  {
    PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "MapViewOfFile failed", GetLastError());
    goto error;
  }

  for (i=0; i < 5; i++)
  {
    strcpy(shm_suffix, StrEvent[i]);
    if (!(pvio_shm->event[i]= OpenEvent(dwDesiredAccess, 0, shm_name)))
    {
      PVIO_SET_ERROR(cinfo->mysql, CR_SHARED_MEMORY_CONNECT_ERROR, "HY000", 0, "Couldn't create event", GetLastError());
      goto error;
    }
  }
  /* we will first read from server */
  SetEvent(pvio_shm->event[PVIO_SHM_SERVER_READ]);

error:
  if (hdlConnectRequest)
    CloseHandle(hdlConnectRequest);
  if (hdlConnectRequestAnswer)
    CloseHandle(hdlConnectRequestAnswer);
  if (shm_name)
    LocalFree(shm_name);
  if (map)
    UnmapViewOfFile(map);
  if (file_map)
    CloseHandle(file_map);
  if (pvio_shm)
  {
    /* check if all events are set */
    if (pvio_shm->event[4])
    {
      pvio->data= (void *)pvio_shm;
      pvio->mysql= cinfo->mysql;
      pvio->type= cinfo->type;
      pvio_shm->read_pos= (char *)pvio_shm->map;
      pvio->mysql->net.pvio= pvio;
      return 0;
    }
    for (i=0;i < 5; i++)
      if (pvio_shm->event[i])
        CloseHandle(pvio_shm->event[i]);
    if (pvio_shm->map)
      UnmapViewOfFile(pvio_shm->map);
    if (pvio_shm->file_map)
      CloseHandle(pvio_shm->file_map);
    LocalFree(pvio_shm);
  }
  return 1;

}
コード例 #7
0
ファイル: shm.c プロジェクト: carsten-clauss/MP-MPICH
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);
}
コード例 #8
0
bool CSingleInstance::NotifyFirstInstance(HWND hwndSender, LPCTSTR commandLine)
{
	DWORD dwTimeout = 30000;
	bool success = true;

	// Try to open the previous instances memory mapped file
	HANDLE hPrevInstance = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, m_mmfilename.c_str());

	// Failed to open previous instance!
	if (!hPrevInstance)
		return false;

	int size = sizeof(SingleInstanceData);
	SingleInstanceData* pInstanceData = static_cast<SingleInstanceData*>(MapViewOfFile(hPrevInstance,
																		 FILE_MAP_READ | FILE_MAP_WRITE,
																		 0,
																		 0,
																		 size));

	if (!pInstanceData)
		return false;

	// Lock the data prior to reading from it
	DWORD dwWaitMutex = WaitForSingleObject(m_hInstanceDataMutex, INFINITE);	
	switch (dwWaitMutex) 
	{
		case WAIT_OBJECT_0: 
		{
			_ASSERT(pInstanceData->hwnd); // Something gone wrong with the MMF

			// Get the first instance hwnd
			HWND hWindow = pInstanceData->hwnd;
			if (hWindow) {

				// Restore the focus to the previous instance and bring it to the foreground
				ShowWindow(hWindow, SW_RESTORE);
				SetForegroundWindow(hWindow);

				if (commandLine)
				{  
					// Send the current instance command line to the previous instance using WM_COPYDATA
					COPYDATASTRUCT cds;
					cds.dwData = NULL;
					DWORD dwCmdLength = static_cast<DWORD>(_tcslen(commandLine) + 1);
					cds.cbData = dwCmdLength * sizeof(TCHAR); 

					// We use a local buffer so that we can specify a constant parameter to this function
					TCHAR* pszLocalCmdLine = new TCHAR[dwCmdLength]; 
					_tcscpy_s(pszLocalCmdLine, dwCmdLength, commandLine);
					cds.lpData = pszLocalCmdLine;

					// Send the message to the previous instance. Use SendMessageTimeout instead of SendMessage to ensure we 
					// do not hang if the previous instance itself is hung
					DWORD_PTR dwResult = 0;
					if (SendMessageTimeout(hWindow,
										   WM_COPYDATA,
										   reinterpret_cast<WPARAM>(hwndSender),
										   reinterpret_cast<LPARAM>(&cds),
										   SMTO_ABORTIFHUNG,
										   dwTimeout,
										   &dwResult) == 0)
					{
						//Previous instance is not responding to messages
						success = false;
					}

					//Tidy up the heap memory we have used
					delete [] pszLocalCmdLine;
				}
			}

			// Unmap the MMF we were using
			UnmapViewOfFile(pInstanceData);

			ReleaseMutex(m_hInstanceDataMutex);
			break;
		}

		default:
			break;
	}

	// When we have activated the previous instance, we can release the lock
	if (success)
		ReleaseLock();

	return success;
}
コード例 #9
0
/******************************************************************************
| Creat mapping to the shared memory for data exchange
******************************************************************************/
int create_mapping(char *ffdDatNam, char *modDatNam)
{
  int i=0, imax=1000;

  /*---------------------------------------------------------------------------
  | Open the FFD file mapping object
  ---------------------------------------------------------------------------*/
  ffdDatMapFil = OpenFileMapping(
                    FILE_MAP_ALL_ACCESS,    // read/write access
                    FALSE,           // do not inherit the name
                    ffdDatNam);    // name of mapping object for FFD data

  while(i<imax && ffdDatMapFil==NULL)
  {
    Sleep(1000);
    ffdDatMapFil = OpenFileMapping(
                    FILE_MAP_ALL_ACCESS,    // read/write access
                    FALSE,           // do not inherit the name
                    ffdDatNam);    // name of mapping object for FFD data
    i++;
  }

  // Send warning if can not open shared memory
  if(ffdDatMapFil==NULL)
  {
    printf("Could not open FFD data file mapping object (%d).\n", GetLastError());
    return GetLastError();
  }

  /*---------------------------------------------------------------------------
  | Maps a view of the FFD file mapping into the address space 
  ---------------------------------------------------------------------------*/
  ffdDatBuf = (ffdDat *) MapViewOfFile(ffdDatMapFil,   // handle to map object
                      FILE_MAP_ALL_ACCESS, // read/write permission
                      0,
                      0,
                      FFD_DATA_SIZE);
  i = 0;
  while(ffdDatBuf==NULL && i<imax)
  {
    Sleep(1000);
    ffdDatBuf = (ffdDat *) MapViewOfFile(ffdDatMapFil,   // handle to map object
                    FILE_MAP_ALL_ACCESS, // read/write permission
                    0,
                    0,
                    FFD_DATA_SIZE);
    i++;
  }

  if(ffdDatBuf==NULL)
  {
    printf("Could not map view of FFD data file (%d).\n", GetLastError());
    CloseHandle(ffdDatMapFil);
    return GetLastError();
  }

  /*---------------------------------------------------------------------------
  | Open the Modelcia file mapping object
  ---------------------------------------------------------------------------*/
  modDatMapFil = OpenFileMapping(
                      FILE_MAP_ALL_ACCESS,    // read/write access
                      FALSE,           // do not inherit the name
                      modDatNam);    // name of mapping object for FFD data
  i = 0;
  while(i<imax && modDatMapFil==NULL)
  {
    Sleep(1000);
    modDatMapFil = OpenFileMapping(
                        FILE_MAP_ALL_ACCESS,    // read/write access
                        FALSE,           // do not inherit the name
                        modDatNam);    // name of mapping object for FFD data
    i++;
  }

  // Send warning if can not open shared memory
  if(modDatMapFil==NULL)
  {
    printf("Could not open Other data file mapping object (%d).", GetLastError());
    return GetLastError();
  }

  /*---------------------------------------------------------------------------
  | Maps a view of the Modelica file mapping into the address space 
  ---------------------------------------------------------------------------*/
  modDatBuf = (modDat *) MapViewOfFile(modDatMapFil,   // handle to map object
                      FILE_MAP_ALL_ACCESS, // read/write permission
                      0,
                      0,
                      MODELICA_DATA_SIZE);
  i = 0;
  while(modDatBuf==NULL && i<imax)
  {
    Sleep(1000);
    modDatBuf = (modDat *) MapViewOfFile(modDatMapFil,   // handle to map object
                    FILE_MAP_ALL_ACCESS, // read/write permission
                    0,
                    0,
                    MODELICA_DATA_SIZE);
    i++;
  }

  if(modDatBuf==NULL)
  {
    printf("Could not map view of Modelcia data file (%d).\n", GetLastError());
    CloseHandle(modDatMapFil);
    return GetLastError();
  }

  return 0;

} // End of create_mapping()
コード例 #10
0
bool CLocalSocket::OpenConnection(void)
{
	bool bRes = false;

	if (!m_connectionEvent.create(m_strConnectionEventName))
		return bRes;
	
	if (!m_inDataHasBeenReadEvent.create(m_strInDataReadEventName))
		return bRes;

	if (!m_outDataHasBeenReadEvent.create(m_strOutDataReadEventName))
		return bRes;

	if (IsServerSocket())
	{
		m_hInMappedBuffer			 =  CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,	m_nBufferSize, m_strLocalSocketName_In.c_str());
		m_hOutMappedBuffer			 =  CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,	m_nBufferSize, m_strLocalSocketName_Out.c_str());
		m_hDisconnectedMappedBuffer  =  CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,	sizeof(s_CommonData), m_strDisconnectedBufferName.c_str());
	}
	else
	{
		m_hInMappedBuffer			=  OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, m_strLocalSocketName_In.c_str());
		m_hOutMappedBuffer			=  OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, m_strLocalSocketName_Out.c_str());
		m_hDisconnectedMappedBuffer =  OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, m_strDisconnectedBufferName.c_str());
		
	}

	if (NULL								== m_hInMappedBuffer
		|| INVALID_HANDLE_VALUE				== m_hInMappedBuffer
		|| NULL								== m_hOutMappedBuffer
		|| INVALID_HANDLE_VALUE				== m_hOutMappedBuffer
		|| NULL								== m_hDisconnectedMappedBuffer
		|| INVALID_HANDLE_VALUE				== m_hDisconnectedMappedBuffer
		)
	{
		// either server or client is unavailable
		return bRes;
	}
	
	if (!m_inDataWrittenEvent.create(m_strInDataEventName))
		return bRes;

	if (!m_outDataWrittenEvent.create(m_strOutDataEventName))
		return bRes;

	if (!m_inDataMutex.create(m_strInDataMutexName))
		return bRes;

	if (!m_outDataMutex.create(m_strOutDataMutexName))
		return bRes;

	if (!m_disconnectedMutex.create(m_strDisconnectedMutexName))
		return bRes;

	// Map to the file
	m_cInDataBuffer		  = (s_PacketBuffer*)MapViewOfFile(m_hInMappedBuffer,	FILE_MAP_ALL_ACCESS, 0, 0, m_nBufferSize);
	m_cOutDataBuffer	  = (s_PacketBuffer*)MapViewOfFile(m_hOutMappedBuffer,	FILE_MAP_ALL_ACCESS, 0, 0, m_nBufferSize);
	m_cDisconnectedBuffer = (s_CommonData*)MapViewOfFile(m_hDisconnectedMappedBuffer,	FILE_MAP_ALL_ACCESS, 0, 0, sizeof(s_CommonData));

	if (NULL							== m_cInDataBuffer
			|| NULL						== m_cOutDataBuffer
			|| NULL						== m_cDisconnectedBuffer
			)
		return bRes;

	bRes = true;

	return bRes;
}
コード例 #11
0
ファイル: Client.cpp プロジェクト: AdesChacal/bwapi
  bool Client::connect()
  {
    if ( this->connected )
    {
      std::cout << "Already connected." << std::endl;
      return true;
    }

    int serverProcID    = -1;
    int gameTableIndex  = -1;

    this->gameTable = NULL;
    this->gameTableFileHandle = OpenFileMapping(FILE_MAP_WRITE | FILE_MAP_READ, FALSE, "Local\\bwapi_shared_memory_game_list" );
    if ( !this->gameTableFileHandle )
    {
      std::cerr << "Game table mapping not found." << std::endl;
      return false;
    }
    this->gameTable = (GameTable*)MapViewOfFile(this->gameTableFileHandle, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, sizeof(GameTable));
    if ( !this->gameTable )
    {
      std::cerr << "Unable to map Game table." << std::endl;
      return false;
    }

    //Find row with most recent keep alive that isn't connected
    DWORD latest = 0;
    for(int i = 0; i < GameTable::MAX_GAME_INSTANCES; i++)
    {
      std::cout << i << " | " << gameTable->gameInstances[i].serverProcessID << " | " << gameTable->gameInstances[i].isConnected << " | " << gameTable->gameInstances[i].lastKeepAliveTime << std::endl;
      if (gameTable->gameInstances[i].serverProcessID != 0 && !gameTable->gameInstances[i].isConnected)
      {
        if ( gameTableIndex == -1 || latest == 0 || gameTable->gameInstances[i].lastKeepAliveTime < latest )
        {
          latest = gameTable->gameInstances[i].lastKeepAliveTime;
          gameTableIndex = i;
        }
      }
    }

    if (gameTableIndex != -1)
      serverProcID = gameTable->gameInstances[gameTableIndex].serverProcessID;

    if (serverProcID == -1)
    {
      std::cerr << "No server proc ID" << std::endl;
      return false;
    }
    
    std::stringstream sharedMemoryName;
    sharedMemoryName << "Local\\bwapi_shared_memory_";
    sharedMemoryName << serverProcID;

    std::stringstream communicationPipe;
    communicationPipe << "\\\\.\\pipe\\bwapi_pipe_";
    communicationPipe << serverProcID;

    pipeObjectHandle = CreateFile(communicationPipe.str().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if ( pipeObjectHandle == INVALID_HANDLE_VALUE )
    {
      std::cerr << "Unable to open communications pipe: " << communicationPipe.str() << std::endl;
      CloseHandle(gameTableFileHandle);
      return false;
    }

    COMMTIMEOUTS c;
    c.ReadIntervalTimeout         = 100;
    c.ReadTotalTimeoutMultiplier  = 100;
    c.ReadTotalTimeoutConstant    = 2000;
    c.WriteTotalTimeoutMultiplier = 100;
    c.WriteTotalTimeoutConstant   = 2000;
    SetCommTimeouts(pipeObjectHandle,&c);

    std::cout << "Connected" << std::endl;
    mapFileHandle = OpenFileMapping(FILE_MAP_WRITE | FILE_MAP_READ, FALSE, sharedMemoryName.str().c_str());
    if (mapFileHandle == INVALID_HANDLE_VALUE || mapFileHandle == NULL)
    {
      std::cerr << "Unable to open shared memory mapping: " << sharedMemoryName.str() << std::endl;
      CloseHandle(pipeObjectHandle);
      CloseHandle(gameTableFileHandle);
      return false;
    }
    data = (GameData*) MapViewOfFile(mapFileHandle, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, sizeof(GameData));
    if ( data == nullptr )
    {
      std::cerr << "Unable to map game data." << std::endl;
      return false;
    }

    // Create new instance of Game/Broodwar
    if ( BWAPI::BroodwarPtr )
      delete static_cast<GameImpl*>(BWAPI::BroodwarPtr);
    BWAPI::BroodwarPtr = new GameImpl(data);
    assert( BWAPI::BroodwarPtr != nullptr );

    if (BWAPI::BWAPI_getRevision() != BWAPI::Broodwar->getRevision())
    {
      //error
      std::cerr << "Error: Client and Server are not compatible!" << std::endl;
      std::cerr << "Client Revision: " << BWAPI::BWAPI_getRevision() << std::endl;
      std::cerr << "Server Revision: " << BWAPI::Broodwar->getRevision() << std::endl;
      disconnect();
      Sleep(2000);
      return false;
    }
    //wait for permission from server before we resume execution
    int code = 1;
    while ( code != 2 )
    {
      DWORD receivedByteCount;
      BOOL success = ReadFile(pipeObjectHandle, &code, sizeof(code), &receivedByteCount, NULL);
      if ( !success )
      {
        disconnect();
        std::cerr << "Unable to read pipe object." << std::endl;
        return false;
      }
    }
    
    std::cout << "Connection successful" << std::endl;
    assert( BWAPI::BroodwarPtr != nullptr);

    this->connected = true;
    return true;
  }
コード例 #12
0
ファイル: ClientKernel.cpp プロジェクト: codercold/whgame
//内核配置
bool __cdecl CClientKernel::InitClientKernel(LPCTSTR lpszComLine, IUnknownEx * pIUnknownEx)
{
	//效验参数
	ASSERT(lpszComLine!=NULL);
	if (lpszComLine==NULL) return false;

	//创建窗口
	if (m_hWnd==NULL) 
	{
		CRect rcCreate(0,0,0,0);
		Create(NULL,NULL,WS_CHILD,rcCreate,GetDesktopWindow(),100);
	}

	//获取框架
	m_pIClientKernelSink=GET_OBJECTPTR_INTERFACE(pIUnknownEx,IClientKernelSink);
	if (m_pIClientKernelSink==NULL) return false;
	m_hWndGameFrame=m_pIClientKernelSink->GetFrameWnd();

	//读取配置
	m_bAllowUserLookon=AfxGetApp()->GetProfileInt(TEXT("GameOption"),TEXT("AllowLookon"),FALSE)?true:false;

	//视频设置
	CVideoServiceManager * pVideoServiceManager=CVideoServiceManager::GetInstance();
	if (pVideoServiceManager!=NULL) pVideoServiceManager->SetClientKernel(GET_OBJECTPTR_INTERFACE(this,IUnknownEx));

	//命令行处理
	if (lpszComLine[0]!=0)
	{
		//提出 TOKEN
		int nStringLength=0;
		CString strRoomToken;
		LPCTSTR pszRoomToken=TEXT("/RoomToken:");
		LPCTSTR lpszBeginString=lpszComLine;
		while (true)
		{
			LPCTSTR lpszEndString=_tcschr(lpszBeginString,TEXT(' '));
			nStringLength=(lpszEndString==NULL)?lstrlen(lpszBeginString):(int)(lpszEndString-lpszBeginString);

			//判断标识
			const int nTokenLength=lstrlen(pszRoomToken);
			if ((nStringLength>=nTokenLength)&&(memcmp(lpszBeginString,pszRoomToken,nTokenLength*sizeof(TCHAR))==0))
			{
				CopyMemory(strRoomToken.GetBufferSetLength(nStringLength-nTokenLength),lpszBeginString+nTokenLength,
					(nStringLength-nTokenLength)*sizeof(TCHAR));
				strRoomToken.ReleaseBuffer();
				break;
			}

			//设置变量
			if (lpszEndString==NULL) break;
			lpszBeginString=(lpszEndString+1);
		}

		//共享内存
		if (strRoomToken.GetLength()>0)
		{
			m_hShareMemory=OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,strRoomToken);
			if (m_hShareMemory==NULL) return false;
			m_pShareMemory=(tagShareMemory *)MapViewOfFile(m_hShareMemory,FILE_MAP_ALL_ACCESS,0,0,0);
			if (m_pShareMemory==NULL) return false;
			if (m_pShareMemory->wDataSize<sizeof(tagShareMemory)) return false;
			m_pShareMemory->hWndGameFrame=m_hWndGameFrame;
		}

		//信道模块
		if (m_hShareMemory!=NULL)
		{
			ASSERT(m_pShareMemory->hWndGameServer!=NULL);
			IUnknownEx * pIUnknownEx=GET_MYSELF_INTERFACE(IUnknownEx);
			if (m_ChannelServiceHelper.CreateInstance()==false) return false;
			if (m_ChannelServiceHelper->SetChannelMessageSink(pIUnknownEx)==false) return false;
			if (m_ChannelServiceHelper->CreateChannel(m_pShareMemory->hWndGameServer)==false) return false;
		}
	}

	//更新标题
	UpdateGameTitle();

	return true;
}
コード例 #13
0
ファイル: ConEmuCheck.cpp プロジェクト: alexlav/conemu
// Returns HWND of ...
//  aiType==0: Gui console DC window
//        ==1: Gui Main window
//        ==2: Console window
HWND GetConEmuHWND(int aiType)
{
	//CESERVER_REQ *pIn = NULL;
	//CESERVER_REQ *pOut = NULL;
	DWORD nLastErr = GetLastError();
	HWND FarHwnd = NULL, ConEmuHwnd = NULL, ConEmuRoot = 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, (DWORD)FarHwnd); //-V205
		#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->hConEmuWnd;
		}

		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);

	if (aiType == 2)
		return FarHwnd;
	else if (aiType == 0)
		return ConEmuHwnd;
	else // aiType == 1
		return ConEmuRoot;
}
コード例 #14
0
ファイル: OpenFileMappingW.c プロジェクト: Afshintm/coreclr
int __cdecl main(int argc, char *argv[])
{
    HANDLE  FileMappingHandle;
    HANDLE  OpenFileMappingHandle;
    HANDLE  lpMapViewAddress;
    HANDLE  OpenFileMappingHandle2;
    HANDLE  lpMapViewAddress2;
    const   int LOWORDERSIZE = 1024;
    WCHAR   MapObject[] = {'m','y','O','b','j','e','c','t','\0'};
    char    buf[] = "this is a test";
    char    ch[1024];
    int     RetVal = PASS;


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

    /* Create a named file-mapping object with file handle FileHandle.
     */
    FileMappingHandle = CreateFileMapping(
                                INVALID_HANDLE_VALUE,
                                NULL,               /* not inherited */
                                PAGE_READWRITE,     /* read and wite */
                                0,                  /* high-order size */
                                LOWORDERSIZE,       /* low-order size */
                                MapObject);         /* named object */

    if(NULL == FileMappingHandle) 
    {
        Fail("\nFailed to call CreateFileMapping to "
             "create a mapping object!\n");
    }
    if(GetLastError() == ERROR_ALREADY_EXISTS)
    {
        Trace("\nFile mapping object already exists!\n");
        RetVal = FAIL;
        goto CleanUpOne;
    }

    /* Open a named file-mapping object with FILE_MAP_WRITE access.
     */
    OpenFileMappingHandle =  OpenFileMapping(
                                    FILE_MAP_WRITE,
                                    FALSE,
                                    MapObject);

    if(NULL == OpenFileMappingHandle)
    {
        Trace("\nFailed to Call OpenFileMappingW API!\n");
        RetVal = FAIL;
        goto CleanUpOne;
    }

    /* Open a named file-mapping object with 
     * FILE_MAP_ALL_ACCESS access, to verify
     * the FILE_MAP_WRITE access map.
     */
    OpenFileMappingHandle2 =  OpenFileMapping(
                                    FILE_MAP_ALL_ACCESS,
                                    FALSE,
                                    MapObject);

    if(NULL == OpenFileMappingHandle2)
    {
        Trace("\nFailed to Call OpenFileMappingW API!\n");
        RetVal = FAIL;
        goto CleanUpTwo;
    }

    /* Create map view of the open mapping that has
     * FILE_MAP_WRITE access.
     */
    lpMapViewAddress = MapViewOfFile(
                            OpenFileMappingHandle,
                            FILE_MAP_WRITE,      /* access code */
                            0,                   /* high order offset */
                            0,                   /* low order offset */
                            LOWORDERSIZE);       /* 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 CleanUpThree;
    }

    /* Create map view of the open mapping that has
     * FILE_MAP_ALL_ACCESS access.
     */
    
    lpMapViewAddress2 = MapViewOfFile(
                            OpenFileMappingHandle2,
                            FILE_MAP_ALL_ACCESS, /* access code */
                            0,                   /* high order offset */
                            0,                   /* low order offset */
                            LOWORDERSIZE);       /* number of bytes for map */

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

    /* Write to the Map View.
     */
    memcpy(lpMapViewAddress, buf, strlen(buf));
    
    /* Read from the Map View.
    */
    memcpy(ch, (LPCSTR)lpMapViewAddress, LOWORDERSIZE); 
    
    /* Compare what was written to the Map View,
     * to what was read.
     */
    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 CleanUpFive;
    }

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

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

CleanUpThree:

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

CleanUpTwo:

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

CleanUpOne:
        
        /* Close Handle to create file mapping.
         */
        if ( CloseHandle(FileMappingHandle) == 0 )
        {
            Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n",
                  GetLastError(),
                  FileMappingHandle);
            RetVal = FAIL;
        }
    
    /* Terminate the PAL.
     */
    PAL_TerminateEx(RetVal);
    return RetVal;
}
コード例 #15
0
/*----------------------------------------------------------------------------
	CheckSakuraFileMapping()
	ファイルマッピングオブジェクトの存在確認
----------------------------------------------------------------------------*/
BOOL CheckSakuraFileMapping(HWND hParentWnd, vector<HWND>& vec)
{
	HANDLE hFileMap;
	LPVOID lpBasePtr;
	LPSTR lpBuffer;
	LPSTR lpType1;
	LPSTR lpType2;
	CHAR szTemp[200];
	DWORD dwSize;
	HWND hWnd = NULL;
	BOOL bRet;

	vec.clear();

	// ファイルマップを開く
	hFileMap = OpenFileMapping(FILE_MAP_READ, FALSE, MY_EXIST_FILEMAP);
	if(hFileMap == NULL) 
	{
		// 存在しない
		//MessageBox(hParentWnd, "ファイルマッピングオブジェクトが開けません。", "TestSSTP", MB_ICONSTOP);
		return FALSE;
	}

	// ベースアドレス取得
	lpBasePtr = (LPVOID)MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0);
	if(lpBasePtr == NULL)
	{
		// 失敗
		//MessageBox(hParentWnd, "ファイルマッピングオブジェクトが操作できません。", "TestSSTP", MB_ICONSTOP);
		CloseHandle(hFileMap);
		return FALSE;
	}
	lpBuffer = (LPSTR)lpBasePtr;

	// データ読み込み
	bRet = TRUE;
	try
	{
		CopyMemory(&dwSize, lpBuffer, sizeof(DWORD));
		lpBuffer += sizeof(DWORD);

		while(*lpBuffer)
		{
			// エントリ解析
			lpType1 = lstrchr(lpBuffer, '.');
			lpType1++;
			lpType2 = lstrchr(lpType1, '\01');
			lpType2++;
			lstrcpyn(szTemp, lpType1, lpType2 - lpType1);

			// エントリの種類ごとに分岐
			if(lstrcmpi(szTemp, "hwnd") == 0)
			{
				// データ取得
				lpType1 = lstrchr(lpType2, '\r');
				lpType1++;
				lstrcpyn(szTemp, lpType2, lpType1 - lpType2);
				hWnd = (HWND)atoi(szTemp);

				vec.push_back(hWnd);
			}

			// \r\n まで1エントリ
			lpBuffer = lstrchr(lpBuffer, '\n');
			if(lpBuffer)
			{
				lpBuffer++;
			}
		}

		bRet = vec.size() > 0 ? TRUE : FALSE;
	}
	catch(...)
	{
		bRet = FALSE;
	}

	UnmapViewOfFile(lpBasePtr);
	CloseHandle(hFileMap);
	return bRet;
}
コード例 #16
0
int _tmain(int argc, _TCHAR* argv[])
{

	DWORD errorCode = 0;


	//OpenMutex(MUTEX_ALL_ACCESS, FALSE, L"DBWinMutex");

	/*
	SECURITY_DESCRIPTOR     sdopen;

	InitializeSecurityDescriptor(&sdopen,SECURITY_DESCRIPTOR_REVISION);
	SetSecurityDescriptorDacl(&sdopen, TRUE, NULL, FALSE);

	SECURITY_ATTRIBUTES     sa;
	ZeroMemory(&sa, sizeof sa);

	sa.nLength = sizeof sa;
	sa.lpSecurityDescriptor = &sdopen;
	sa.bInheritHandle = FALSE;

	if ((hMutex = CreateMutex(&sa, FALSE, L"DBWinMutex")) == 0)
	{

	errorCode = GetLastError();
	printf("createmutex error %d", errorCode);
	return errorCode;
	}
	*/


	hEventBufferReady = OpenEvent(EVENT_ALL_ACCESS, FALSE, L"DBWIN_BUFFER_READY");
	if (hEventBufferReady == NULL) {
		hEventBufferReady = CreateEvent(NULL, FALSE, TRUE, L"DBWIN_BUFFER_READY");

		if (hEventBufferReady == NULL) {
			errorCode = GetLastError();
			printf("buffer ready error %d", errorCode);
			return errorCode;
		}
	}


	hEventDataReady = OpenEvent(SYNCHRONIZE, FALSE, L"DBWIN_DATA_READY");
	if (hEventDataReady == NULL) {
		hEventDataReady = CreateEvent(NULL, FALSE, FALSE, L"DBWIN_DATA_READY");

		if (hEventDataReady == NULL) {
			errorCode = GetLastError();
			printf("ready data error %d", errorCode);
			return errorCode;
		}
	}


	hDBWINBuffer = OpenFileMapping(FILE_MAP_READ, FALSE, L"DBWIN_BUFFER");


	if (hDBWINBuffer == NULL) {
		hDBWINBuffer = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(struct db_buffer), L"DBWIN_BUFFER");

		if (hDBWINBuffer == NULL) {
			errorCode = GetLastError();
			printf("create file mapping error %d", errorCode);
			return errorCode;
		}
	}

	pDBBuffer = (struct db_buffer *)MapViewOfFile(hDBWINBuffer, SECTION_MAP_READ, 0, 0, 0);

	if (pDBBuffer == NULL) {
		errorCode = GetLastError();
		printf("map view of file error %d", errorCode);
		return errorCode;
	}

	bool isRunning = true;
	while (isRunning)
	{

		DWORD mb = WaitForSingleObject(hEventDataReady, INFINITE);

		if (mb == WAIT_OBJECT_0) {

			printf("%s", pDBBuffer->data);
			SetEvent(hEventBufferReady);
		}

	}

	UnmapViewOfFile(pDBBuffer);
	CloseHandle(hDBWINBuffer);
	CloseHandle(hEventBufferReady);
	CloseHandle(hEventDataReady);
	//CloseHandle(hMutex);
	//hMutex = 0;

	return 0;
}
コード例 #17
0
ファイル: Map.cpp プロジェクト: ivankhm/lpProject
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;
	static int x = 0, y = 0;
	static TCHAR buf[10];
	static HANDLE hFileMap;
	PVOID pView;
	static bool isOpen = false, isSelect = false;

	if (isOpen && isSelect){
		if (hFileMap != NULL){
			if ((pView = MapViewOfFile(hFileMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0)) != NULL){
				wsprintf(buf, L"%s", (PTSTR)pView);
				UnmapViewOfFile(pView);
				InvalidateRect(hWnd, NULL, TRUE);
			}
			else
				MessageBox(hWnd, L"Error of view!", MB_OK, NULL);
		}
		else
			MessageBox(hWnd, L"Error of opening!", MB_OK, NULL);
	}

	switch (message)
	{
	case WM_MOUSEMOVE:
		if (isSelect && !isOpen){
			x = LOWORD(lParam);
			y = HIWORD(lParam);
			wsprintf(buf, L"%d %d", x, y);
			InvalidateRect(hWnd, NULL, TRUE);

			if (hFileMap != NULL){
				PVOID pView = MapViewOfFile(hFileMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
				if (pView != NULL){
					wsprintf((PTSTR)pView, L"%s", buf);
					UnmapViewOfFile(pView);
				}
				else
					MessageBox(hWnd, L"Error of view!", MB_OK, NULL);
			}
			else
				MessageBox(hWnd, L"Error of create mapping file!", MB_OK, NULL);
		}
		break;
	case WM_COMMAND:
		wmId = LOWORD(wParam);
		wmEvent = HIWORD(wParam);

		switch (wmId)
		{
		case IDM_INFO_IN:
			isOpen = false;
			hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
				PAGE_READWRITE, 0, 1 * 1024, TEXT("MMFSharedData"));
			isSelect = true;
			break;
		case IDM_INFO_OUT:
			isOpen = true;
			hFileMap = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, TEXT("MMFSharedData"));
			if (MapViewOfFile(hFileMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0) != NULL)
				isSelect = true;
			else
				MessageBox(hWnd, L"Maping file didn't create!", MB_OK, NULL);
			break;
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		TextOut(hdc, 10, 10, buf, lstrlenW(buf));
		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		CloseHandle(hFileMap);
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
コード例 #18
0
ファイル: BUShm.cpp プロジェクト: nykma/ykt4sungard
void * CBUShm::Open(const char *name, int shmsize)
{
    char buf[256];
    Close();
    sprintf(buf,"%s.shm",name);
    m_fileno = sh_open(buf,O_CREAT|O_RDWR,SH_DENYNO);
    if (m_fileno==-1)
    {
        sprintf(m_szmsg,"Cannot open SHM File for '%s' size=%d",name,shmsize);
        return(NULL);
    }
#ifdef WIN32
    if (shmsize>0)
    {
        m_shmid = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,shmsize,(LPCSTR)name);
        if (m_shmid==NULL)
        {
            // 共享内存创建错误:
            sprintf(m_szmsg,"Cannot open share memory for SHM(%s) size=%d -errno:%u!",name,shmsize,GetLastError());
            Close();
            return(NULL);
        }
    }
    else
    {
        m_shmid = OpenFileMapping(FILE_MAP_WRITE|FILE_MAP_READ,FALSE,(LPCSTR)name);
        if (m_shmid==NULL)
        {
            sprintf(m_szmsg,"Cannot open share memory for SHM(%s) - errno:%u!",name,GetLastError());
            Close();
            return(NULL);
        }
    }
    m_address = MapViewOfFile(m_shmid,FILE_MAP_WRITE|FILE_MAP_READ,0,0,0);
    if (m_address==NULL)
    {
        sprintf(m_szmsg,"MapViewOfFile fail [SHM(%s) size=%d] - errno:%u!",name,shmsize,GetLastError());
        Close();
        return(NULL);
    }
    BY_HANDLE_FILE_INFORMATION finfo;
    GetFileInformationByHandle(m_shmid,&finfo);
    m_size = finfo.nFileSizeLow;
    return(m_address);
#else
    bool bcreated = true;
    key_t shmkey = myftok(buf,BUSHM_KID);
    if (shmsize>0)
    {
        m_shmid = shmget(shmkey,shmsize,SHM_RIGHT|IPC_CREAT);
    }
    else
        m_shmid = -1;
    if (m_shmid==-1)
    {
        m_shmid = shmget(shmkey,0,BUSHM_FLAG);
        bcreated = false;
    }
    if (m_shmid==-1)
    {
        // 共享内存创建错误:
        sprintf(m_szmsg,"Cannot open share memory for key:0x%X-errno:%d!",shmkey,errno);
        Close();
        return(NULL);
    }
    m_address = shmat(m_shmid,0,0);
#ifdef SHM_FAILED //11:50 2006-7-4 for HP_UX64 
    if (m_address==SHM_FAILED)
#else
    if (m_address==(void *)-1L)
#endif
    {
        m_address = NULL;
        // 则表示挂接的地址出现问题,可能属于flag不正确的缘故
        sprintf(m_szmsg,"shmkey=%x:shmat(%d,0,0) 返回错误errno=%d!",shmkey,m_shmid,errno);
        Close();
        if (bcreated)
            Remove(name);
    }
    struct shmid_ds info;
    shmctl(m_shmid,IPC_STAT,&info);
    m_size = info.shm_segsz;
    return(m_address);
#endif
}
コード例 #19
0
    bool RunCmd(LPCWSTR lpszCmdLine, wstring& strOutput, int nShowCmd, DWORD dwWaitTime)
    {
        bool fRet = false;
        DWORD dwRet = 0;
        UINT nRet = 0;
        HANDLE hEvent = INVALID_HANDLE_VALUE;
        HANDLE hFileOutputSize = NULL;
        HANDLE hFile = NULL;
        DWORD* pdwOutputSize = NULL;
        DWORD dwOutputSize = 0;
        BYTE* pOutput = NULL;
        wstring strMyCmdExePath;

        strOutput.clear();

        if ((!lpszCmdLine) || (!_tcslen(lpszCmdLine)))
            goto END;

        fRet = GetFullPathRelativeToCurrentModule(MY_CMD_EXE, strMyCmdExePath);
        if ((!fRet) || (!PathFileExists(strMyCmdExePath.c_str())))
            goto END;

        nRet = (UINT)ShellExecute(NULL, NULL, strMyCmdExePath.c_str(), lpszCmdLine, NULL, nShowCmd);
        if (nRet <= 32)
            goto END;

        hEvent = CreateEvent(NULL, false, false, MY_CMD_OUTPUT_EVENT);
        if (hEvent == INVALID_HANDLE_VALUE)
            goto END;

        dwRet = WaitForSingleObject(hEvent, dwWaitTime);
        if (dwRet != WAIT_OBJECT_0)
            goto END;

        hFileOutputSize = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, MY_CMD_OUTPUT_SIZE_FILE_MAPPING);
        if (!hFileOutputSize)
            goto END;

        pdwOutputSize = (DWORD*)MapViewOfFile(hFileOutputSize, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(DWORD));
        if (!pdwOutputSize)
            goto END;

        dwOutputSize = *pdwOutputSize; 

        hFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, MY_CMD_OUTPUT_FILE_MAPPING);
        if (!hFile)
            goto END;

        pOutput = (BYTE*)MapViewOfFile(hFile, FILE_MAP_ALL_ACCESS, 0, 0, dwOutputSize);
        if (dwOutputSize)
            strOutput = (TCHAR*)pOutput;

        // ---------- Done -----------
        fRet = true;

    END:
        if ((hEvent) && (hEvent != INVALID_HANDLE_VALUE))  
            CloseHandle(hEvent);

        if (pdwOutputSize)
            UnmapViewOfFile(pdwOutputSize);

        if (pOutput)
            UnmapViewOfFile(pOutput);

        if (hFileOutputSize)
            CloseHandle(hFileOutputSize);

        if (hFile)
            CloseHandle(hFile);

        return fRet;
    }
コード例 #20
0
ファイル: tracker.c プロジェクト: johnh530/electro
int acquire_tracker(int t_key, int c_key, int port)
{
    /* Acquire the tracker and controller shared memory segments. */

#ifndef _WIN32
    if ((tracker_id = shmget(t_key, sizeof (struct tracker_header), 0)) >= 0)
        tracker = (struct tracker_header *) shmat(tracker_id, 0, 0);

    if ((control_id = shmget(c_key, sizeof (struct control_header), 0)) >= 0)
        control = (struct control_header *) shmat(control_id, 0, 0);
#else
    char shmkey[256];

    sprintf(shmkey, "%d", t_key);
    if ((tracker_id = OpenFileMapping(FILE_MAP_WRITE, FALSE, shmkey)))
        tracker = (struct tracker_header *)
                    MapViewOfFile(tracker_id, FILE_MAP_WRITE, 0, 0, 0);
    else
        tracker = (struct tracker_header *) (-1);

    sprintf(shmkey, "%d", c_key);
    if ((control_id = OpenFileMapping(FILE_MAP_WRITE, FALSE, shmkey)))
        control = (struct control_header *)
                    MapViewOfFile(control_id, FILE_MAP_WRITE, 0, 0, 0);
    else
        control = (struct control_header *) (-1);
#endif

    /* Allocate storage for button states. */

    if (control != (struct control_header *) (-1))
        buttons = (uint32_t *) calloc(control->but_count, sizeof (uint32_t));

    /* Open a UDP socket for receiving. */

    if (port)
    {
        if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) >= 0)
        {
            sockaddr_t addr;

            /* Accept connections from any address on the given port. */

            addr.sin_family      = AF_INET;
            addr.sin_port        = htons((short) port);
            addr.sin_addr.s_addr = htonl(INADDR_ANY);

            /* Bind the socket to this address. */

            if (bind(sock, (struct sockaddr *) &addr, sizeof (sockaddr_t))>= 0)
            {
                transforms = 1;
            }
            else error("bind %d : %s", port, system_error());
        }
        else error("socket : %s", system_error());
    }

    /* Initialize the tracker transform. */

    if (tracker != (struct tracker_header *) (-1))
        new_tracker_transforms((int) tracker->count);

    return 1;
}
コード例 #21
0
ファイル: ossShMem.cpp プロジェクト: 2015520/SequoiaDB
CHAR *ossSHMAlloc( ossSHMKey shmKey, UINT32 bufSize, INT32 shmFlag, ossSHMMid &shmMid )
{
   CHAR *pBuf = NULL;
#if defined (_LINUX)
   shmMid = shmget( shmKey,bufSize, shmFlag | 0666 );
   if ( shmMid < 0 )
   {
      perror("shmget");
      goto error;
   }
   pBuf = (CHAR *)shmat( shmMid, (const void*)0, 0 );
   if ( (CHAR *)-1 == pBuf )
   {
      shmctl( shmMid, IPC_RMID, 0 );
      pBuf = NULL;
   }
#elif defined (_WINDOWS)
   wchar_t *pKey = NULL;
   UINT32 keySize = MultiByteToWideChar(CP_ACP, 0, shmKey, -1, NULL, 0 );
   if ( keySize <= 0 )
   {
      goto error;
   }
   pKey = new wchar_t[keySize];
   if ( NULL == pKey )
   {
      goto error;
   }
   MultiByteToWideChar(CP_ACP, 0, shmKey, -1, pKey, keySize );
   shmMid = OpenFileMapping( FILE_MAP_ALL_ACCESS, FALSE, pKey );
   if ( NULL == shmMid )
   {
      if ( shmFlag | OSS_SHM_CREATE )
      {
         shmMid = CreateFileMapping( INVALID_HANDLE_VALUE,
                                    NULL,
                                    PAGE_READWRITE,
                                    0,
                                    bufSize,
                                    pKey );
      }
   }
   else
   {
      if ( ( shmFlag | OSS_SHM_CREATE )
            && ( shmFlag | OSS_SHM_EXCL ) )
      {
         CloseHandle( shmMid );
         goto error;
      }
   }
   if ( NULL == shmMid )
   {
      goto error;
   }
   pBuf = (char *)MapViewOfFile( shmMid,
                                 FILE_MAP_ALL_ACCESS,
                                 0,
                                 0,
                                 bufSize );
   if ( NULL == pBuf )
   {
      CloseHandle( shmMid );
      shmMid = NULL;
   }
#endif
done:
#if defined (_WINDOWS)
   if ( pKey != NULL )
   {
      delete[] pKey;
   }
#endif
   return pBuf;
error:
   goto done;
}
コード例 #22
0
ファイル: main.cpp プロジェクト: TinkerWorX/kkapture
static void init()
{
  bool error = true;
  HANDLE hMapping = OpenFileMapping(FILE_MAP_READ,FALSE,_T("__kkapture_parameter_block"));
  if(hMapping == 0) // no parameter block available.
    return;

  InitializeCriticalSection(&shuttingDown);

  // initialize params with all zero (ahem)
  initLog();
  printLog("main: initializing...\n");
  memset(&params,0,sizeof(params));

  // get file mapping containing capturing info
  ParameterBlock *block = (ParameterBlock *) MapViewOfFile(hMapping,FILE_MAP_READ,0,0,sizeof(ParameterBlock));
  if(block)
  {
    // correct version
    if(block->VersionTag == PARAMVERSION)
    {
      memcpy(&params,block,sizeof(params));
      error = false;
    }

    UnmapViewOfFile(block);
  }

  CloseHandle(hMapping);

  // if kkapture is being debugged, wait for the user to attach the debugger to this process
  if(params.IsDebugged)
  {
    // create message window
    HWND waiting = CreateWindowEx(0,"STATIC",
      "Please attach debugger now.",WS_POPUP|WS_DLGFRAME|SS_CENTER|SS_CENTERIMAGE,0,0,240,50,0,0,
      GetModuleHandle(0),0);
    SendMessage(waiting,WM_SETFONT,(WPARAM) GetStockObject(DEFAULT_GUI_FONT),TRUE);

    // center it
    RECT rcWork,rcDlg;
    SystemParametersInfo(SPI_GETWORKAREA,0,&rcWork,0);
    GetWindowRect(waiting,&rcDlg);
    SetWindowPos(waiting,0,(rcWork.left+rcWork.right-rcDlg.right+rcDlg.left)/2,
      (rcWork.top+rcWork.bottom-rcDlg.bottom+rcDlg.top)/2,-1,-1,SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);

    // show it and wait for user to attach debugger
    ShowWindow(waiting,SW_SHOW);

    while(!IsDebuggerPresent())
    {
      MSG msg;

      while(PeekMessage(&msg,0,0,0,PM_REMOVE))
      {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
      }
      
      Sleep(10);
    }

    // user has attached the debugger, bring window to foreground then destroy it
    SetForegroundWindow(waiting);
    ShowWindow(waiting,SW_HIDE);

    MessageBox(waiting,"Debugger attached, set any breakpoints etc. you need to and press OK.","kkapture",
      MB_ICONINFORMATION|MB_OK);

    DestroyWindow(waiting);
  }

  // rest of initialization code
  initTiming(true);
  initVideo();
  initSound();
  initProcessIntercept();
  printLog("main: all main components initialized.\n");

  if(error)
  {
    printLog("main: couldn't access parameter block or wrong version\n");

    frameRateScaled = 1000;
    frameRateDenom = 100;
    encoder = new DummyVideoEncoder;
  }
  else
  {
    printLog("main: reading parameter block...\n");

    frameRateScaled = params.FrameRateNum;
    frameRateDenom = params.FrameRateDenom;
    encoder = 0;
  }

  // install our hook so we get notified of process exit (hopefully)
  HookFunction(&Real_ExitProcess, Mine_ExitProcess);
  hHookThread = (HANDLE) _beginthread(HookThreadProc,0,0);

  initialized = true;

  printLog("main: initialization done\n");
}
コード例 #23
0
HRESULT STDMETHODCALLTYPE CFunctionProfiler::Initialize( 
    /* [in] */ IUnknown *pICorProfilerInfoUnk) 
{
    ATLTRACE(_T("::Initialize"));

    m_profilerInfo2 = pICorProfilerInfoUnk;
    if (m_profilerInfo2 != NULL) ATLTRACE(_T("    ::Initialize (m_profilerInfo2 OK)"));
    if (m_profilerInfo2 == NULL) return E_FAIL;
    m_profilerInfo3 = pICorProfilerInfoUnk;
    if (m_profilerInfo3 != NULL) ATLTRACE(_T("    ::Initialize (m_profilerInfo3 OK)"));

    TCHAR tag[100];
    ::ZeroMemory(tag, 100);
    ::GetEnvironmentVariable(_T("MMProfiler_Tag"), tag, 100);
    tstring wTag(tag);

    HANDLE hMapControlFile = OpenFileMapping(
        FILE_MAP_ALL_ACCESS,
        false,
        (_T("Local\\MMProfilerMapControl") + wTag).c_str()
        );

    if (hMapControlFile == NULL)
    {
        ATLTRACE(_T("    Failed to open control map file (GetLastError => %d)"), ::GetLastError());
        return E_FAIL;
    }

    m_hMapFile = OpenFileMapping(
        FILE_MAP_ALL_ACCESS,
        false,
        (_T("Local\\MMProfilerMapBuffer") + wTag).c_str()
        );

    if(m_hMapFile == NULL)
    {
        ATLTRACE(_T("    Failed to open buffer map file (GetLastError => %d)"), ::GetLastError());
        return E_FAIL;
    }

    m_hReadBufferEvent.Initialise((_T("Local\\MM_ReadBuffer") + wTag).c_str());
    if (!m_hReadBufferEvent.IsValid())
    {
        ATLTRACE(_T("failed to open event m_hReadBufferEvent (GetLastError => %d)"), ::GetLastError());
        return E_FAIL;
    }

    m_hBufferReadEvent.Initialise((_T("Local\\MM_BufferRead") + wTag).c_str());
    if (!m_hBufferReadEvent.IsValid())
    {
        ATLTRACE(_T("failed to open event m_hBufferReadEvent (GetLastError => %d)"), ::GetLastError());
        return E_FAIL;
    }
    m_hBufferReadEvent.Reset();

    m_hProcessMutex.Initialise((_T("Local\\MM_Profiler_BufferAccess") + wTag).c_str());
    if (!m_hProcessMutex.IsValid())
    {
        ATLTRACE(_T("failed to open mutex m_hProcessMutex (GetLastError => %d)"), ::GetLastError());
        return E_FAIL;
    }

    ProfilerData *profilerData = (ProfilerData*)MapViewOfFile(
        hMapControlFile,
        FILE_MAP_ALL_ACCESS,
        0,
        0,
        sizeof(ProfilerData)
        ); 

    boost::split(m_excludes, profilerData->excludes, boost::is_any_of(L", "));
    m_excludes.remove_if(IsEmpty);
    m_excludes.push_front(L"System");
    m_excludes.push_front(L"mscorlib");

    boost::split(m_includes, profilerData->includes, boost::is_any_of(L", "));
    m_includes.remove_if(IsEmpty);

    m_bufferSize = profilerData->bufferSize;
    m_thresholdSize = profilerData->thresholdSize;

    for (std::list<tstring>::iterator it = m_includes.begin(); it != m_includes.end(); ++it)
    {
        ATLTRACE(_T("include => %s"), (*it).c_str());
    }
    for (std::list<tstring>::iterator it = m_excludes.begin(); it != m_excludes.end(); ++it)
    {
        ATLTRACE(_T("exclude => %s"), (*it).c_str());
    }

    if (profilerData!=NULL) 
    {
        UnmapViewOfFile(profilerData);
    }
    CloseHandle(hMapControlFile);

    m_pView = (BYTE*)MapViewOfFile(
        m_hMapFile,
        FILE_MAP_ALL_ACCESS,
        0,
        0,
        m_bufferSize + m_thresholdSize + sizeof(int)
        );

    if (m_pView == NULL)
    {
        ATLTRACE(_T("Failed to map view file (GetLastError => %d)"), ::GetLastError());
        return E_FAIL;
    }

    ATLTRACE(_T("LISTS - Include %d, Exclude %d"), m_includes.size(), m_excludes.size());

    DWORD dwMask = 0;
    dwMask |= COR_PRF_MONITOR_ENTERLEAVE;           // Controls the FunctionEnter, FunctionLeave, and FunctionTailcall callbacks.
    dwMask |= COR_PRF_ENABLE_FRAME_INFO;            // ensures that we have frameinfo in the callback (important for generics)

    m_profilerInfo2->SetEventMask(dwMask);

    if(m_profilerInfo3 != NULL)
        m_profilerInfo3->SetFunctionIDMapper2(FunctionMapper2, this);
    else
        m_profilerInfo2->SetFunctionIDMapper(FunctionMapper);

    m_formatBuffer = m_pView + sizeof(long);
    m_currentBuffer = m_formatBuffer;

    g_pProfiler = this;

    m_profilerInfo2->SetEnterLeaveFunctionHooks2(
        _FunctionEnter2, 
        _FunctionLeave2, 
        _FunctionTailcall2);

    return S_OK;
}
コード例 #24
0
ファイル: main.cpp プロジェクト: u338steven/afxtools
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
	HANDLE hSharedBuffer = CreateFileMapping(
			INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
			0, MAX_URL, __SHAREDMEM_NAME__);
	if (hSharedBuffer != NULL) {
		_SharedBufer = (char*)::MapViewOfFile(hSharedBuffer, FILE_MAP_ALL_ACCESS, 0, 0, MAX_URL);
	}
	if (::GetLastError() == ERROR_ALREADY_EXISTS) {
		hSharedBuffer = OpenFileMapping( FILE_MAP_ALL_ACCESS, TRUE, __SHAREDMEM_NAME__);
		if (hSharedBuffer != NULL) {
			_SharedBufer = (char*)::MapViewOfFile(hSharedBuffer, FILE_MAP_ALL_ACCESS, 0, 0, MAX_URL);
			memset(_SharedBufer, 0, MAX_URL);
			strncpy(_SharedBufer, lpCmdLine, MAX_URL-1);
			_hAfxBrwsEvent = ::OpenEvent(EVENT_ALL_ACCESS, FALSE, __EVENT_NAME__);
			if (_hAfxBrwsEvent != NULL) {
				::SetEvent(_hAfxBrwsEvent);
				::CloseHandle(_hAfxBrwsEvent);
			}
			::UnmapViewOfFile(_SharedBufer);
			::CloseHandle(hSharedBuffer);
		}
		return -1;
	}

	_hAfxWnd = ::FindWindow(_T("TAfxWForm"), NULL);
	if (_hAfxWnd == INVALID_HANDLE_VALUE) {
		_hAfxWnd = ::FindWindow(_T("TAfxForm"), NULL);
		if (_hAfxWnd == INVALID_HANDLE_VALUE) {
			::UnmapViewOfFile(_SharedBufer);
			::CloseHandle(hSharedBuffer);
			return -1;
		}
	}

	char ini_path[MAX_PATH];
	GetModuleFileName(NULL, ini_path, sizeof(ini_path));
	int len = strlen(ini_path);
	if (len+2 >= MAX_PATH) {
		return -1;
	}
	ini_path[len-3] = 'i';
	ini_path[len-2] = 'n';
	ini_path[len-1] = 'i';
	_stay_mode = ::GetPrivateProfileInt("Config",  "stay", 1, ini_path);

	_hAfxBrwsEvent = ::CreateEvent(NULL, FALSE, FALSE, __EVENT_NAME__);

	RECT rect;
	::GetWindowRect(_hAfxWnd, &rect);
	IEComponent ie(_hAfxWnd, hInstance, 0, 0, rect.right - rect.left, rect.bottom - rect.top);
	ie.LoadPage(lpCmdLine);
	_hBroWnd = ie.GetWndIE();
	SetFocusOtherProcess(ie.GetWndIE());
	IOleInPlaceActiveObject* actObj = ie.GetActObj();
	_ie = &ie;

	DWORD thId1;
	_hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Thread1, NULL, 0, &thId1);

	MSG	msg;
	while (GetMessage (&msg, NULL, 0, 0))
	{
		if (actObj->TranslateAccelerator(&msg)) {
			TranslateMessage (&msg);
			DispatchMessage (&msg);
		}
	}

	if (_fullscreen) {
		::MoveWindow(_hAfxWnd, 
			_rect_pre_fullscreen.left,
			_rect_pre_fullscreen.top,
			_rect_pre_fullscreen.right - _rect_pre_fullscreen.left,
			_rect_pre_fullscreen.bottom - _rect_pre_fullscreen.top,
			TRUE);
	}

	_thread_exit = TRUE;
	::WaitForSingleObject(_hThread, INFINITE);
	::CloseHandle(_hAfxBrwsEvent);
	::UnmapViewOfFile(_SharedBufer);
	::CloseHandle(hSharedBuffer);
	::CloseHandle(_hThread);

	SetFocusOtherProcess(_hAfxWnd);

	return msg.wParam;
};
コード例 #25
0
ファイル: shared_alloc_win32.c プロジェクト: jpauli/php-src
static int create_segments(size_t requested_size, zend_shared_segment ***shared_segments_p, int *shared_segments_count, char **error_in)
{
	int err = 0, 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));
		if (memfile == NULL) {
			err = GetLastError();
			break;
		}

		ret =  zend_shared_alloc_reattach(requested_size, error_in);
		if (ret == ALLOC_FAIL_MAPPING) {
			err = GetLastError();
			/* 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) {
		err = GetLastError();
		zend_shared_alloc_unlock_win32();
		zend_win_error_message(ACCEL_LOG_FATAL, "calloc() failed", err);
		*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));
	if (memfile == NULL) {
		err = GetLastError();
		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) {
		wanted_mapping_base = vista_mapping_base_set;
	} 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);

	if (mapping_base == NULL) {
		err = GetLastError();
		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");
		if (!fp) {
			err = GetLastError();
			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;
}
コード例 #26
0
ファイル: TeleportLib.cpp プロジェクト: BeneDev/VRProject
        SharedMemoryHandle()
        {
            for (int attempt = 0; attempt < 10; attempt++)
            {
                bool clearmemory = true;
                char filename[1024];

#if UNITY_WIN

                sprintf_s(filename, "UnityAudioTeleport%d", attempt);
                hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(SharedMemory), filename);
                if (hMapFile == NULL)
                {
                    clearmemory = false;
                    hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, filename);
                }
                if (hMapFile == NULL)
                {
                    printf("Could not create file mapping object (%d).\n", GetLastError());
                    continue;
                }

                data = (SharedMemory*)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(SharedMemory));
                if (data == NULL)
                {
                    printf("Could not map view of file (%d).\n", GetLastError());
                    CloseHandle(hMapFile);
                    continue;
                }

#else
#if UNITY_LINUX
                // a shared memory object should be identified by a name of the form /somename;
                // that is, a null-terminated string of up to NAME_MAX (i.e.,  255)  characters consisting of an initial slash,
                // followed by one or more characters, none of which are slashes.
                sprintf(filename, "/UnityAudioTeleport%d", attempt);
#else
                sprintf(filename, "/tmp/UnityAudioTeleport%d", attempt);
#endif
                clearmemory = (access(filename, F_OK) == -1);
                int handle = shm_open(filename, O_RDWR | O_CREAT, 0777);
                if (handle == -1)
                {
                    fprintf(stderr, "Open failed: %s\n", strerror(errno));
                    continue;
                }

                if (ftruncate(handle, sizeof(SharedMemory)) == -1)
                {
                    fprintf(stderr, "ftruncate error (ignored)\n");
                    //continue;
                }

                data = (SharedMemory*)mmap(0, sizeof(SharedMemory), PROT_READ | PROT_WRITE, MAP_SHARED, handle, 0);
                if (data == (void*)-1)
                {
                    fprintf(stderr, "mmap failed\n");
                    continue;
                }

                //close(handle);
                //shm_unlink(filename);

#endif

                if (clearmemory)
                    memset(data, 0, sizeof(SharedMemory));

                break; // intentional (see continue's above)
            }
        }
コード例 #27
0
ファイル: SynchObj.c プロジェクト: jiangguang5201314/ZNginx
static SYNCHHANDLE AllocSynchHandle (LPCTSTR lpName,
                                     LPTSTR MutexName, LPTSTR EventName, LPTSTR MutexaName,
                                     LPBOOL pfNewObject)
/*	Allocate memory for a synchronization handle. Unnamed objects
	have their handles created directly in the process heap, whereas
	named objects have two handles, one allocated locally to
	contain the handles (which are local to this process) and
	out of a shared memory pool mapped to the paging file for
	the shared object state.
	Also, create the names for the three internal objects
	and determine if this is a new object that should be initialized. */
{
    HANDLE hSynchDB;	/*  Mutex to protect the entire synchronization object database */
    HANDLE hMap, hFile;
    /*	Shared memory and file handle for maintaining synch objects */
    BOOL FirstTime;
    SYNCHHANDLE pView, pNew = NULL, pFirstFree, hLocal;

    hLocal = HeapAlloc (GetProcessHeap(), HEAP_ZERO_MEMORY, SYNCH_HANDLE_SIZE);
    if (hLocal == NULL) return NULL;
    *pfNewObject = TRUE;
    if (lpName == NULL || _tcscmp (lpName, _T("")) == 0)
    {
        /*  The object is not named */
        hLocal->SharedHandle = NULL;
        return hLocal;
    }

    /*	The object is named. Create names for the internal objects. */
    _stprintf (MutexName,  _T("%s%s"), lpName, _T(".mtx"));
    _stprintf (EventName,  _T("%s%s"), lpName, _T(".evt"));
    _stprintf (MutexaName, _T("%s%s"), lpName, _T(".mtxa"));

    /*	Lock access to the synchronization object data base to prevent other threads
    	from concurrently creating another object of the same name.
    	All processes and threads use this same well-known mutex name. */

    hSynchDB = CreateMutex (NULL, FALSE, SYNCH_OBJECT_MUTEX);
    WaitForSingleObject (hSynchDB, INFINITE);

    /*  Access the shared memory where the synchronization objects are maintained.
    	It is necessary, however, first to check if this is the first time
    	that an object has been created so that the shared memory-mapped
    	table can be initialized.
    	The test is achieved with an OpenFileMapping call.  */

    __try
    {
        hMap = OpenFileMapping (FILE_MAP_WRITE, FALSE, SYNCH_FM_NAME);
        FirstTime = (hMap == NULL);
        if (FirstTime) /* Fix this!! hFile was never created */
            hMap = CreateFileMapping (hFile, NULL, PAGE_READWRITE, 0, SIZE_SYNCH_DB, SYNCH_FM_NAME);
        if (hMap == NULL) _leave;
        pView = (SYNCHHANDLE)MapViewOfFile (hMap, FILE_MAP_WRITE, 0, 0, SIZE_SYNCH_DB);
        if (pView == NULL) _leave;
        if (FirstTime) memset (pView, 0, SIZE_SYNCH_DB);

        /*	Search to see if an object of this name already exists.
        	The entry the mapped record is used for bookkeeping, in
        	case it is ever needed in the future. An empty slot
        	is detected by a 0 reference count. */
        pFirstFree = NULL;
        for (pNew = pView+1; pNew < pView + SYNCH_MAX_NUMBER; pNew++)
        {
            if ((pFirstFree == NULL) && (pNew->RefCount <= 0)) pFirstFree = pNew;
            if ((pNew->lpName != NULL)
                    && _tcscmp (pNew->lpName, lpName) == 0) break; /* Name exists */
        }

        if (pNew < pView + SYNCH_MAX_NUMBER)   /* The name exists */
        {
            *pfNewObject = FALSE;
        }
        else if (pFirstFree != NULL)
        {
            /*	The name does not exist, but we have found and empty slot. */
            *pfNewObject = TRUE;
            pNew = pFirstFree;
        }
        else     /*  The name does not exist, but there is no free slot. */
        {
            pNew = NULL;
            *pfNewObject = TRUE;
        }
    }

    __finally
    {
        if (pNew != NULL) hLocal->ViewOfFile = pView;
        hLocal->SharedHandle = pNew;
        if (hLocal->SharedHandle != NULL)
            InterlockedIncrement (&(hLocal->SharedHandle->RefCount));
        ReleaseMutex (hSynchDB);
    }
    return hLocal;
}
コード例 #28
0
ファイル: tsrm_win32.c プロジェクト: Distrotech/php-src
TSRM_API int shmget(int key, int size, int flags)
{
	shm_pair *shm;
	char shm_segment[26], shm_info[29];
	HANDLE shm_handle, info_handle;
	BOOL created = FALSE;

	if (size < 0) {
		return -1;
	}

	snprintf(shm_segment, sizeof(shm_segment), "TSRM_SHM_SEGMENT:%d", key);
	snprintf(shm_info, sizeof(shm_info), "TSRM_SHM_DESCRIPTOR:%d", key);

	shm_handle  = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, shm_segment);
	info_handle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, shm_info);

	if (!shm_handle && !info_handle) {
		if (flags & IPC_CREAT) {
			shm_handle	= CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, size, shm_segment);
			info_handle	= CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(shm->descriptor), shm_info);
			created		= TRUE;
		}
		if (!shm_handle || !info_handle) {
			if (shm_handle) {
				CloseHandle(shm_handle);
			}
			if (info_handle) {
				CloseHandle(info_handle);
			}
			return -1;
		}
	} else {
		if (flags & IPC_EXCL) {
			return -1;
		}
	}

	shm = shm_get(key, NULL);
	if (!shm) {
		CloseHandle(shm_handle);
		CloseHandle(info_handle);
		return -1;
	}
	shm->segment = shm_handle;
	shm->info	 = info_handle;
	shm->descriptor = MapViewOfFileEx(shm->info, FILE_MAP_ALL_ACCESS, 0, 0, 0, NULL);

	if (NULL != shm->descriptor && created) {
		shm->descriptor->shm_perm.key	= key;
		shm->descriptor->shm_segsz		= size;
		shm->descriptor->shm_ctime		= time(NULL);
		shm->descriptor->shm_cpid		= getpid();
		shm->descriptor->shm_perm.mode	= flags;

		shm->descriptor->shm_perm.cuid	= shm->descriptor->shm_perm.cgid= 0;
		shm->descriptor->shm_perm.gid	= shm->descriptor->shm_perm.uid = 0;
		shm->descriptor->shm_atime		= shm->descriptor->shm_dtime	= 0;
		shm->descriptor->shm_lpid		= shm->descriptor->shm_nattch	= 0;
		shm->descriptor->shm_perm.mode	= shm->descriptor->shm_perm.seq	= 0;
	}

	if (NULL != shm->descriptor && (shm->descriptor->shm_perm.key != key || size > shm->descriptor->shm_segsz)) {
		if (NULL != shm->segment) {
			CloseHandle(shm->segment);
		}
		UnmapViewOfFile(shm->descriptor);
		CloseHandle(shm->info);
		return -1;
	}

	return key;
}
コード例 #29
0
tShbError  ShbIpcAllocBuffer (
    unsigned long ulBufferSize_p,
    const char* pszBufferID_p,
    tShbInstance* ppShbInstance_p,
    unsigned int* pfShbNewCreated_p)
{

HANDLE          hSharedMem;
LPVOID          pSharedMem;
unsigned long   ulShMemSize;
tShbMemInst*    pShbMemInst = NULL;
tShbMemHeader*  pShbMemHeader;
tShbInstance    pShbInstance;
unsigned int    fShMemNewCreated;
const char*     pszObjectName;
HANDLE          hMutexBuffAccess;
HANDLE          hEventNewData;
HANDLE          hEventJobReady;
tShbError       ShbError;


    ulShMemSize      = ulBufferSize_p + sizeof(tShbMemHeader);
    pSharedMem       = NULL;
    pShbInstance     = NULL;
    fShMemNewCreated = FALSE;
    ShbError         = kShbOk;


    //---------------------------------------------------------------
    // (1) open an existing or create a new shared memory
    //---------------------------------------------------------------
    // try to open an already existing shared memory
    // (created by an another process)
    hSharedMem = OpenFileMapping (FILE_MAP_ALL_ACCESS,      // DWORD dwDesiredAccess
                                  FALSE,                    // BOOL bInheritHandle
                                  pszBufferID_p);           // LPCTSTR lpName
    if (hSharedMem != NULL)
    {
        // a shared memory already exists
        fShMemNewCreated = FALSE;
    }
    else
    {
        // it seams that this process is the first who wants to use the
        // shared memory, so it has to create a new shared memory
        hSharedMem = CreateFileMapping(INVALID_HANDLE_VALUE,// HANDLE hFile
                                       NULL,                // LPSECURITY_ATTRIBUTES lpAttributes
                                       PAGE_READWRITE,      // DWORD flProtect
                                       0,                   // DWORD dwMaximumSizeHigh
                                       ulShMemSize,         // DWORD dwMaximumSizeLow
                                       pszBufferID_p);      // LPCTSTR lpName

        fShMemNewCreated = TRUE;
    }

    if (hSharedMem == NULL)
    {
        ShbError = kShbOutOfMem;
        goto Exit;
    }


    //---------------------------------------------------------------
    // (2) get the pointer to the shared memory
    //---------------------------------------------------------------
    pSharedMem = MapViewOfFile (hSharedMem,                 // HANDLE hFileMappingObject
                                FILE_MAP_ALL_ACCESS,        // DWORD dwDesiredAccess,
                                0,                          // DWORD dwFileOffsetHigh,
                                0,                          // DWORD dwFileOffsetLow,
                                ulShMemSize);               // SIZE_T dwNumberOfBytesToMap

    if (pSharedMem == NULL)
    {
        ShbError = kShbOutOfMem;
        goto Exit;
    }


    //---------------------------------------------------------------
    // (3) setup or update header and management information
    //---------------------------------------------------------------
    pShbMemHeader = (tShbMemHeader*)pSharedMem;

    // allocate a memory block from process specific mempool to save
    // process local information to administrate/manage the shared buffer
    pShbMemInst = (tShbMemInst*) ShbIpcAllocPrivateMem (sizeof(tShbMemInst));
    if (pShbMemInst == NULL)
    {
        ShbError = kShbOutOfMem;
        goto Exit;
    }

    // reset complete header to default values
    pShbMemInst->m_SbiMagicID                          = SBI_MAGIC_ID;
    pShbMemInst->m_hSharedMem                          = hSharedMem;
    pShbMemInst->m_hMutexBuffAccess                    = INVALID_HANDLE_VALUE;
    pShbMemInst->m_hThreadNewData                      = INVALID_HANDLE_VALUE;
    pShbMemInst->m_ahEventNewData[IDX_EVENT_NEW_DATA]  = INVALID_HANDLE_VALUE;
    pShbMemInst->m_ahEventNewData[IDX_EVENT_TERM_REQU] = INVALID_HANDLE_VALUE;
    pShbMemInst->m_ahEventNewData[IDX_EVENT_TERM_RESP] = INVALID_HANDLE_VALUE;
    pShbMemInst->m_pfnSigHndlrNewData                  = NULL;
    pShbMemInst->m_hThreadJobReady                     = INVALID_HANDLE_VALUE;
    pShbMemInst->m_hEventJobReady                      = INVALID_HANDLE_VALUE;
    pShbMemInst->m_ulTimeOutMsJobReady                 = 0;
    pShbMemInst->m_pfnSigHndlrJobReady                 = NULL;
    pShbMemInst->m_pShbMemHeader                       = pShbMemHeader;

    #ifndef NDEBUG
    {
        pShbMemInst->m_ulThreadIDNewData  = 0;
        pShbMemInst->m_ulThreadIDJobReady = 0;
    }
    #endif

    // create mutex for buffer access
    pszObjectName = ShbIpcGetUniformObjectName (NAME_MUTEX_BUFF_ACCESS, pszBufferID_p, TRUE);
    hMutexBuffAccess = CreateMutex (NULL,                   // LPSECURITY_ATTRIBUTES lpMutexAttributes
                                    FALSE,                  // BOOL bInitialOwner
                                    pszObjectName);         // LPCTSTR lpName
    pShbMemInst->m_hMutexBuffAccess = hMutexBuffAccess;
    ASSERT(pShbMemInst->m_hMutexBuffAccess != NULL);

    // The EventNewData is used for signaling of new data after a write
    // operation (SetEvent) as well as for waiting for new data on the
    // reader side (WaitForMultipleObjects). Because it's not known if
    // this process will be read or write data, the event will be
    // always created here.
    pszObjectName = ShbIpcGetUniformObjectName (NAME_EVENT_NEW_DATA, pszBufferID_p, TRUE);
    hEventNewData = CreateEvent (NULL,                      // LPSECURITY_ATTRIBUTES lpEventAttributes
                                 FALSE,                     // BOOL bManualReset
                                 FALSE,                     // BOOL bInitialState
                                 pszObjectName);            // LPCTSTR lpName
    pShbMemInst->m_ahEventNewData[IDX_EVENT_NEW_DATA] = hEventNewData;
    ASSERT(pShbMemInst->m_ahEventNewData[IDX_EVENT_NEW_DATA] != NULL);

    // The EventJobReady is used for signaling that a job is done (SetEvent)
    // as well as for waiting for finishing of a job (WaitForMultipleObjects).
    // Because it's not known if this process will signal or wait, the event
    // will be always created here.
    pszObjectName = ShbIpcGetUniformObjectName (NAME_EVENT_JOB_READY, pszBufferID_p, TRUE);
    hEventJobReady = CreateEvent (NULL,                     // LPSECURITY_ATTRIBUTES lpEventAttributes
                                  FALSE,                    // BOOL bManualReset
                                  FALSE,                    // BOOL bInitialState
                                  pszObjectName);           // LPCTSTR lpName
    pShbMemInst->m_hEventJobReady = hEventJobReady;
    ASSERT(pShbMemInst->m_hEventJobReady != NULL);

    if ( fShMemNewCreated )
    {
        // this process was the first who wanted to use the shared memory,
        // so a new shared memory was created
        // -> setup new header information inside the shared memory region
        //    itself
        pShbMemHeader->m_SbhMagicID  = SBH_MAGIC_ID;
        pShbMemHeader->m_ulShMemSize = ulShMemSize;
        pShbMemHeader->m_ulRefCount  = 1;
        pShbMemHeader->m_pShbInstMaster = NULL;
        strcpy_s (pShbMemHeader->m_szBufferID, sizeof(pShbMemHeader->m_szBufferID), pszBufferID_p);

        #ifndef NDEBUG
        {
            pShbMemHeader->m_ulOwnerProcID = GetCurrentProcessId();
        }
        #endif
    }
    else
    {
        // any other process has created the shared memory and this
        // process has only attached to it
        // -> check and update existing header information inside the
        //    shared memory region itself
        if (pShbMemHeader->m_ulShMemSize != ulShMemSize)
        {
            ShbError = kShbOpenMismatch;
            goto Exit;
        }

        #ifndef NDEBUG
        {
            if ( strncmp(pShbMemHeader->m_szBufferID, pszBufferID_p, sizeof(pShbMemHeader->m_szBufferID)-1) )
            {
                ShbError = kShbOpenMismatch;
                goto Exit;
            }
        }
        #endif

        pShbMemHeader->m_ulRefCount++;
    }


    // set abstarct "handle" for returning to application
    pShbInstance = (tShbInstance*)pShbMemInst;


Exit:

    if (ShbError != kShbOk)
    {
        if (pShbMemInst != NULL)
        {
            ShbIpcReleasePrivateMem (pShbMemInst);
        }
        if (pSharedMem != NULL)
        {
            UnmapViewOfFile (pSharedMem);
        }
        if (hSharedMem != NULL)
        {
            CloseHandle (hSharedMem);
        }
    }

    *pfShbNewCreated_p = fShMemNewCreated;
    *ppShbInstance_p   = pShbInstance;

    return (ShbError);

}
コード例 #30
-2
ファイル: ssqueue.cpp プロジェクト: dong777/EasyPlayer
int		SSQ_Init(SS_QUEUE_OBJ_T *pObj, unsigned int sharememory, unsigned int channelid, wchar_t *sharename, unsigned int bufsize, unsigned int prerecordsecs, unsigned int createsharememory)
{
	wchar_t wszHeaderName[36] = {0,};
	wchar_t wszFramelistName[36] = {0,};
	wchar_t wszDataName[36] = {0,};
	if (NULL==pObj)											return -1;
	if (createsharememory==0x01 && bufsize<1)				return -1;
	if ( (sharememory==0x01) && (NULL==sharename || (0==wcscmp(sharename, TEXT("\0")))) )	return -1;

	memset(pObj, 0x00, sizeof(SS_QUEUE_OBJ_T));
	pObj->channelid = channelid;
	pObj->shareinfo.id = channelid;
	wcscpy(pObj->shareinfo.name, sharename);

	wchar_t wszMutexName[36] = {0,};
	wsprintf(wszMutexName, TEXT("%s%d_mutex"), sharename, channelid);
	pObj->hMutex = OpenMutex(NULL, FALSE, wszMutexName);
	if (NULL == pObj->hMutex)
	{
		pObj->hMutex = CreateMutex(NULL, FALSE, wszMutexName);
		if (NULL == pObj->hMutex)							return -1;
	}

	//Create Header map
	
	
#ifdef _WIN32
	if (sharememory == 0x01)
	{
		wsprintf(wszHeaderName, TEXT("%s%d_h"), sharename, channelid);
		pObj->hSSHeader = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, wszHeaderName);
		if (NULL==pObj->hSSHeader && createsharememory==0x01)
		{
			pObj->hSSHeader = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE|SEC_COMMIT, 0, sizeof(SS_HEADER_T), wszHeaderName);
			if (NULL==pObj->hSSHeader || pObj->hSSHeader==INVALID_HANDLE_VALUE)
			{
				return -1;
			}
		}
		pObj->pQueHeader = (SS_HEADER_T*)MapViewOfFile(pObj->hSSHeader, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 0);
		if (createsharememory==0x01)
		{
			if (pObj->pQueHeader->bufsize < 1)
			{
				memset(pObj->pQueHeader, 0x00, sizeof(SS_HEADER_T));
				pObj->pQueHeader->bufsize = bufsize;
			}
		}
		else if (NULL==pObj->pQueHeader)
		{
			return -1;
		}
		else
		{
			bufsize = pObj->pQueHeader->bufsize;
 		}
	}
	else
	{
		pObj->pQueHeader = new SS_HEADER_T;
		memset(pObj->pQueHeader, 0x00, sizeof(SS_HEADER_T));
	}

	//==========================================
	//Create frame list map
	if (prerecordsecs > 0)
	{
		wsprintf(wszFramelistName, TEXT("%s%d_f"), sharename, channelid);
		unsigned int nFramelistNum = prerecordsecs * 30;	//每秒30帧
		unsigned int nFrameQueSize = nFramelistNum*sizeof(FRAMEINFO_LIST_T);

		if (sharememory == 0x01)
		{
			pObj->hSSFrameList = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, wszFramelistName);
			if (NULL==pObj->hSSFrameList && createsharememory==0x01)
			{
				pObj->hSSFrameList = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE|SEC_COMMIT, 0, nFrameQueSize, wszFramelistName);
				if (NULL==pObj->hSSFrameList || pObj->hSSFrameList==INVALID_HANDLE_VALUE)
				{
					return -1;
				}
			}
			pObj->pFrameinfoList = (FRAMEINFO_LIST_T*)MapViewOfFile(pObj->hSSFrameList, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 0);
			if (createsharememory==0x01)
			{
				memset(pObj->pFrameinfoList, 0x00, nFrameQueSize);
				pObj->pQueHeader->framelistNum = nFramelistNum;
			}
			else if (NULL==pObj->hSSFrameList)
			{
				return -1;
			}
		}
		else
		{
			pObj->pFrameinfoList = new FRAMEINFO_LIST_T[nFramelistNum];
			memset(&pObj->pFrameinfoList[0], 0x00, sizeof(FRAMEINFO_LIST_T)*nFramelistNum);
			pObj->pQueHeader->framelistNum = nFramelistNum;
		}
	}

	//Create data map
	
	if (sharememory == 0x01)
	{
		wsprintf(wszDataName, TEXT("%s%d_b"), sharename, channelid);
		pObj->hSSData	= OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, wszDataName);
		if (NULL==pObj->hSSData && createsharememory==0x01)
		{
			pObj->hSSData = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE|SEC_COMMIT, 0, bufsize, wszDataName);
		}
		if (NULL == pObj->hSSData || pObj->hSSData==INVALID_HANDLE_VALUE)
		{
			return -1;
		}
		pObj->pQueData = (char*)MapViewOfFile(pObj->hSSData, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 0);
	}
	else
	{
		pObj->pQueData = new char [bufsize];
		pObj->pQueHeader->bufsize = bufsize;
	}
	if (createsharememory==0x01)
	{
		//memset(pQueHeader, 0x00, sizeof(SS_HEADER_T));
		memset(pObj->pQueData, 0x00, bufsize);
	}
#else
	int ret = shm_create((SYNC_VID_SHM_KEY<<8)|channelid, &pObj->shmHdrid, sizeof(SS_HEADER_T), (char**)&pObj->pQueHeader);
	if (ret < 0)
	{
		return -1;
	}
	SSQ_TRACE("[%d]pQueHeader: %d\n", (SYNC_VID_SHM_KEY<<8)|channelid, pObj->shmHdrid);
	ret = shm_create((SYNC_VID_SHM_KEY<<16)|channelid, &pObj->shmDatid, bufsize, (char**)&pObj->pQueData);
	if (ret < 0)
	{
		shm_delete(&pObj->shmHdrid, (char*)pObj->pQueHeader);
		return -1;
	}
	pObj->pQueHeader->bufsize = bufsize;
	SSQ_TRACE("[%d]pQueData: %d\n", (SYNC_VID_SHM_KEY<<16)|channelid, pObj->shmDatid);
#endif

	return 0;
}