/*********************************************************************** * OpenFileMappingA (KERNEL32.@) * * Opens a named file-mapping object. * * PARAMS * access [I] Access mode. * inherit [I] Inherit flag. * name [I] Name of file-mapping object. * * RETURNS * Success: Handle. * Failure: NULL. */ HANDLE WINAPI OpenFileMappingA( DWORD access, BOOL inherit, LPCSTR name ) { WCHAR buffer[MAX_PATH]; if (!name) return OpenFileMappingW( access, inherit, NULL ); if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH )) { SetLastError( ERROR_FILENAME_EXCED_RANGE ); return 0; } return OpenFileMappingW( access, inherit, buffer ); }
bool MumbleLink::init() { assert(mumbleLinkedMemory == nullptr); #ifdef WIN32 priv->obj = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, L"MumbleLink"); if (priv->obj == nullptr) return false; mumbleLinkedMemory = static_cast<MumbleLinkedMemory *>(MapViewOfFile( priv->obj, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(*mumbleLinkedMemory))); if (mumbleLinkedMemory == nullptr) { CloseHandle(priv->obj); priv->obj = nullptr; return false; } #else std::string name = "/MumbleLink." + std::to_string(getuid()); priv->fd = shm_open(name.c_str(), O_RDWR, S_IRUSR | S_IWUSR); if (priv->fd < 0) { return false; } mumbleLinkedMemory = static_cast<MumbleLinkedMemory *>( (mmap(nullptr, sizeof(*mumbleLinkedMemory), PROT_READ | PROT_WRITE, MAP_SHARED, priv->fd, 0))); if (mumbleLinkedMemory == MAP_FAILED) { mumbleLinkedMemory = nullptr; return false; } #endif return true; }
void initMumble() { #ifdef WIN32 HANDLE hMapObject = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, L"MumbleLink"); if (hMapObject == NULL) return; lm = (LinkedMem *) MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(LinkedMem)); if (lm == NULL) { CloseHandle(hMapObject); hMapObject = NULL; return; } #else char memname[256]; snprintf(memname, 256, "/MumbleLink.%d", getuid()); int shmfd = shm_open(memname, O_RDWR, S_IRUSR | S_IWUSR); if (shmfd < 0) { return; } lm = (LinkedMem *)(mmap(NULL, sizeof(struct LinkedMem), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd,0)); if (lm == (void *)(-1)) { lm = NULL; return; } #endif }
bool IPCContext::init() { if (NULL == (m_hMutex = OpenMutexW(SYNCHRONIZE, false, HOOKSGRABBER_MUTEX_MEM_NAME))) { m_logger->reportLogError(L"error occured while opening mutex 0x%x", GetLastError()); this->free(); return false; } if (NULL == (m_hSharedMem = OpenFileMappingW(GENERIC_WRITE | GENERIC_READ, false, HOOKSGRABBER_SHARED_MEM_NAME))) { m_logger->reportLogError(L"error occured while opening memory-mapped file 0x%x", GetLastError()); this->free(); return false; } if (NULL == (m_hFrameGrabbedEvent = CreateEventW(NULL, true, false, HOOKSGRABBER_FRAMEGRABBED_EVENT_NAME))) { m_logger->reportLogError(L"error occured while opening event 0x%x", GetLastError()); this->free(); return false; } m_pMemMap = MapViewOfFile(m_hSharedMem, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, HOOKSGRABBER_SHARED_MEM_SIZE); if (m_pMemMap == NULL) { m_logger->reportLogError(L"error occured while creating mapview 0x%x", GetLastError()); this->free(); return false; } m_pMemDesc = (HOOKSGRABBER_SHARED_MEM_DESC*)m_pMemMap; return true; }
// 获得灰名单 bool CDriverCommunicator::GetGrayFile(set<wstring>& file) { const int size = 6000;//暂时够用了 char sfile[size]; if( CGetOSInfo::getInstance()->isX64() )//64bits OS { HANDLE mphd = NULL; mphd = OpenFileMappingW(FILE_MAP_READ, FALSE, L"SHAREGRAYMEM"); if(mphd) { LPVOID lpMapAddr = MapViewOfFile(mphd,FILE_MAP_READ,0,0,0); if(lpMapAddr) { file.insert( (wchar_t*)((UCHAR*)lpMapAddr+sizeof(ULONG)) ); /*char buf[MAX_PATH] = {0};////D unsigned char *hash1 = (UCHAR*)lpMapAddr+sizeof(ULONG)+sizeof(wchar_t)*2; sprintf(buf," address is : %x get gray hash is: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", hash1, hash1[0], hash1[1], hash1[2], hash1[3], hash1[4], hash1[5], hash1[6], hash1[7], hash1[8], hash1[9], hash1[10], hash1[11], hash1[12], hash1[13], hash1[14], hash1[15]) ; OutputDebugStringA(buf);*/ return true; } else { int error = GetLastError(); CRecordProgram::GetInstance()->FeedbackError(MY_PRO_NAME, MY_THREAD_DRIVER_COM, CRecordProgram::GetInstance()->GetRecordInfo(L"MapViewOfFile SHAREGRAYMEM error:%d", error)); return false; } } else { int error = GetLastError(); CRecordProgram::GetInstance()->FeedbackError(MY_PRO_NAME, MY_THREAD_DRIVER_COM, CRecordProgram::GetInstance()->GetRecordInfo(L"OpenFileMapping SHAREGRAYMEM error:%d", error)); return false; } } else { if(BankLoader::GetGrayFile((void*)sfile,size)) { DWORD num = 0; memcpy(&num, sfile ,sizeof(DWORD)); char* p = sfile + sizeof(DWORD); for(DWORD dwIndex = 0; dwIndex < num; dwIndex ++) // gao { WCHAR strfile[MAX_PATH] = { 0 }; memcpy((void*)strfile, p,sizeof(strfile)); file.insert(strfile); p = p + sizeof(strfile) + 16; } return true; } else return false; } }
void Mumble_CreateLink() { #ifdef _WIN32 if (hMapObject != NULL) { ST_Printf(PRINT_FAIL,"Mumble link already initialized.\n"); return; } hMapObject = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, L"MumbleLink"); if (hMapObject == NULL) { //Com_Printf("Mumble is not running\n"); return; } lm = (struct LinkedMem *) MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(struct LinkedMem)); if (lm == NULL) { CloseHandle(hMapObject); hMapObject = NULL; ST_Printf(PRINT_FAIL,"Mumble link initialization failed.\n"); return; } #else // Linux && Mac char memname[256]; if (lm != NULL) { ST_Printf(PRINT_FAIL,"Mumble link already initialized.\n"); return; } snprintf(memname, 256, "/MumbleLink.%d", getuid()); shmfd = shm_open(memname, O_RDWR, S_IRUSR | S_IWUSR); if(shmfd < 0) { ST_Printf(PRINT_INFO,"Mumble initialization skipped. Mumble not running.\n"); return; } lm = (struct LinkedMem *) (mmap(NULL, sizeof(struct LinkedMem), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd,0)); if (lm == (void *) (-1)) { lm = NULL; close(shmfd); shmfd = -1; ST_Printf(PRINT_FAIL,"Mumble link initialization failed.\n"); return; } #endif mbstowcs(lm->name, "jQuake", sizeof(lm->name)); Com_Printf(CharsToBrownStatic("Mumble link initialized.")); Com_Printf("\n"); }
int mumble_link( const char *name ) { #ifdef WIN32 if ( lm ) { return 0; } hMapObject = OpenFileMappingW( FILE_MAP_ALL_ACCESS, FALSE, L"MumbleLink" ); if ( hMapObject == NULL ) { return -1; } lm = ( LinkedMem * ) MapViewOfFile( hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, sizeof( LinkedMem ) ); if ( lm == NULL ) { CloseHandle( hMapObject ); hMapObject = NULL; return -1; } #else char file[ 256 ]; int shmfd; if ( lm ) { return 0; } snprintf( file, sizeof( file ), "/MumbleLink.%d", getuid() ); shmfd = shm_open( file, O_RDWR, S_IRUSR | S_IWUSR ); if ( shmfd < 0 ) { return -1; } lm = ( LinkedMem * )( mmap( NULL, sizeof( LinkedMem ), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0 ) ); if ( lm == ( void * )( -1 ) ) { lm = NULL; close( shmfd ); return -1; } close( shmfd ); #endif memset( lm, 0, sizeof( LinkedMem ) ); mbstowcs( lm->name, name, sizeof( lm->name ) ); return 0; }
static bool shm_create(impl_type& impl,const String& name_,size_t size_,int flag_) { HANDLE hMapFile; if(flag_&FLAG_FILE_CR) { FileAccess::LargeInteger tmp; tmp.dval=size_; hMapFile = CreateFileMappingW( INVALID_HANDLE_VALUE, // Use paging file - shared memory NULL, // Default security attributes PAGE_READWRITE, // Allow read and write access tmp.d[1], // High-order DWORD of file mapping max size tmp.d[0], // Low-order DWORD of file mapping max size name_.empty()?NULL:IConv::to_wide(name_).c_str() ); } else { hMapFile = OpenFileMappingW( FileAccess::makeflag(flag_,FILE_MAP_READ,FILE_MAP_WRITE), FALSE, // Do not inherit the name IConv::to_wide(name_).c_str() // File mapping name ); } if (hMapFile == NULL) { System::CheckError("CreateFileMapping/OpenFileMapping"); return false; } char* pView = (char*)MapViewOfFile( hMapFile, // Handle of the map object FileAccess::makeflag(flag_,FILE_MAP_READ,FILE_MAP_WRITE), // access 0, // High-order DWORD of the file offset 0, // Low-order DWORD of the file offset size_ // The number of bytes to map to view ); if(!pView) { ::CloseHandle(hMapFile); System::CheckError("MapViewOfFile"); return false; } impl.m_pAddr=pView; impl.m_nSize=size_; impl.m_sName=name_; impl.m_pHandle.reset(hMapFile); return true; }
DBWin::DBWin(DWORD pid = -1) { initialized = false; processId = pid; hMutex = OpenMutexW(SYNCHRONIZE, FALSE, L"DBWinMutex"); if (!hMutex) { std::cerr << "Failed opening DBWinMutex" << std::endl; return; } hBufferReady = OpenEventW(EVENT_ALL_ACCESS, FALSE, L"DBWIN_BUFFER_READY"); if (!hBufferReady) { hBufferReady = CreateEventW(nullptr, FALSE, TRUE, L"DBWIN_BUFFER_READY"); if (!hBufferReady) { std::cerr << "Failed to open or create DBWIN_BUFFER_READY" << std::endl; return; } } hDataReady = OpenEventW(EVENT_ALL_ACCESS, FALSE, L"DBWIN_DATA_READY"); if (!hDataReady) { hDataReady = CreateEventW(nullptr, FALSE, FALSE, L"DBWIN_DATA_READY"); if (!hDataReady) { std::cerr << "Failed to open or create DBWIN_DATA_READY" << std::endl; return; } } hBuffer = OpenFileMappingW(FILE_MAP_READ, FALSE, L"DBWIN_BUFFER"); if (!hBuffer) { hBuffer = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, sizeof(dbwin_buffer), L"DBWIN_BUFFER"); if (!hBuffer) { std::cerr << "Failed to open or create DBWIN_BUFFER" << std::endl; return; } } dbBuffer = static_cast<dbwin_buffer*>(MapViewOfFile(hBuffer, SECTION_MAP_READ, 0, 0, 0)); if (!dbBuffer) { std::cerr << "Failed to map memory to dbBuffer" << std::endl; return; } initialized = true; }
HANDLE APIENTRY OpenFileMappingA( DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName ) /*++ Routine Description: ANSI thunk to OpenFileMappingW --*/ { PUNICODE_STRING Unicode; ANSI_STRING AnsiString; NTSTATUS Status; if ( ARGUMENT_PRESENT(lpName) ) { Unicode = &NtCurrentTeb()->StaticUnicodeString; RtlInitAnsiString(&AnsiString,lpName); Status = RtlAnsiStringToUnicodeString(Unicode,&AnsiString,FALSE); if ( !NT_SUCCESS(Status) ) { if ( Status == STATUS_BUFFER_OVERFLOW ) { SetLastError(ERROR_FILENAME_EXCED_RANGE); } else { BaseSetLastNTError(Status); } return NULL; } } else { BaseSetLastNTError(STATUS_INVALID_PARAMETER); return NULL; } return OpenFileMappingW( dwDesiredAccess, bInheritHandle, (LPCWSTR)Unicode->Buffer ); }
void *open_shared_mem(LPCWSTR name, DWORD size, HANDLE *hmap) { HANDLE map; void *ptr; map = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, name); if(map == NULL) { return NULL; } ptr = MapViewOfFile(map, FILE_MAP_ALL_ACCESS, 0, 0, size); if(ptr != NULL) { *hmap = map; } return ptr; }
bool SharedMemory::open(const wchar_t *_nm, size_t _sz, bool _open) { if(good()) close(); mSize = 0; mPtr = NULL; if(_open) { mFile = OpenFileMappingW(FILE_MAP_WRITE, FALSE, _nm); } else { mFile = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, _sz, _nm); } if(!mFile) { DWORD err = GetLastError(); return false; } mPtr = MapViewOfFile(mFile, FILE_MAP_WRITE, 0, 0, _sz); if(!mPtr) { CloseHandle(mFile); mFile = 0; return false; } mSize = _sz; return true; }
void LinkPlugin::InitializeLinkedMem() { #ifdef WIN32 HANDLE hMapObject = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, L"MumbleLink"); if (hMapObject == NULL) { reason_ = "Shared memory is not available, please ensure that mumble client is running."; return; } linked_mem_ = (LinkedMem *) MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(LinkedMem)); if (linked_mem_ == NULL) { CloseHandle(hMapObject); hMapObject = NULL; reason_ = "Shared memory is not available, cannot open the file."; return; } #else char memname[256]; snprintf(memname, 256, "/MumbleLink.%d", getuid()); int shmfd = shm_open(memname, O_RDWR, S_IRUSR | S_IWUSR); if (shmfd < 0) { reason_ = "Shared memory is not available, please ensure that mumble client is running."; return; } linked_mem_ = (LinkedMem *)(mmap(NULL, sizeof(struct LinkedMem), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd,0)); if (linked_mem_ == (void *)(-1)) { reason_ = "Shared memory is not available, cannot open the file."; linked_mem_ = NULL; return; } #endif }
/* * @implemented */ HANDLE NTAPI OpenFileMappingA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName) { NTSTATUS Status; ANSI_STRING AnsiName; PUNICODE_STRING UnicodeCache; /* Check for a name */ if (lpName) { /* Use TEB Cache */ UnicodeCache = &NtCurrentTeb()->StaticUnicodeString; /* Convert to unicode */ RtlInitAnsiString(&AnsiName, lpName); Status = RtlAnsiStringToUnicodeString(UnicodeCache, &AnsiName, FALSE); if (!NT_SUCCESS(Status)) { /* Conversion failed */ BaseSetLastNTError(Status); return NULL; } } else { /* We need a name */ SetLastError(ERROR_INVALID_PARAMETER); return NULL; } /* Call the Unicode version */ return OpenFileMappingW(dwDesiredAccess, bInheritHandle, (LPCWSTR)UnicodeCache->Buffer); }
void CMumbleSystem::LevelInitPostEntity() { if ( g_pMumbleMemory ) return; #if defined( WIN32 ) && !defined( _X360 ) g_hMapObject = OpenFileMappingW( FILE_MAP_ALL_ACCESS, FALSE, L"MumbleLink" ); if ( g_hMapObject == NULL ) return; g_pMumbleMemory = (MumbleSharedMemory_t *) MapViewOfFile( g_hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(MumbleSharedMemory_t) ); if ( g_pMumbleMemory == NULL ) { CloseHandle( g_hMapObject ); g_hMapObject = NULL; return; } #elif defined( POSIX ) char memname[256]; V_sprintf_safe( memname, "/MumbleLink.%d", getuid() ); int shmfd = shm_open( memname, O_RDWR, S_IRUSR | S_IWUSR ); if ( shmfd < 0 ) { return; } g_pMumbleMemory = (MumbleSharedMemory_t *)( mmap( NULL, sizeof(struct MumbleSharedMemory_t), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd,0 ) ); if ( g_pMumbleMemory == (void *)(-1) ) { g_pMumbleMemory = NULL; return; } #endif }
LRESULT IpcListenerWnd::_WindowProcCopy(const COPYDATASTRUCT& cds) { try { // try and decrypt the message that was sent. IpcData ipcRequest(static_cast<unsigned char*>(cds.lpData), cds.cbData); // just call the handler IpcData ipcResponse(ipcRequest.GetGuid()); if( !_handler.HandleIpcMessage( ipcRequest, ipcResponse ) ) { return 0; } // did we get a guid, if we do then we need to send the response back to the sender. if (!ipcRequest.HasGuid()) { // we do not have a guid, but it is still a success. // the user might not expect a response. return 1; } // try and open the file map, it should be opened by the sender. // if not, then there is an error somewhere. auto hMapFile = OpenFileMappingW(FILE_MAP_ALL_ACCESS, false, ipcRequest.GetGuid().c_str()); if (hMapFile == nullptr) { // we _did_ get a guid, but we could not open it. // so this is no longer a success. return 0; } // get the buffer. auto pBuf = static_cast<unsigned char*>(MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, 1000 )); if (pBuf != nullptr) { // get the response pointer. auto pData = ipcResponse.GetPtr(); // the data size, we must make sure it is 4bytes // a signed int in c# is 4 bytes and should also be in c++ auto datasize = static_cast<signed int>(ipcResponse.GetSize()); #ifdef DEBUG assert(sizeof(datasize) == 4); #endif // DEBUG memcpy(pBuf, &datasize, sizeof(datasize)); // now add the data itself. memcpy(pBuf + sizeof(datasize), pData, datasize); // clean the buffer. UnmapViewOfFile(pBuf); } CloseHandle(hMapFile); } catch (...) { // received some invalid data. return 0; } // success return 1; }
BOOL CDllInjectClient::Connect( CONST WCHAR * aKey , PFN_DLL_INJECT_CLIENT_INIT_CBK aInitCbk ) { DbgOut( VERB , DBG_DLL_INJECT_MGR , "Enter. aKey=%ws" , aKey ); _ASSERT( aKey ); BOOL bRet = FALSE; HANDLE hSmInit = NULL; DLL_INJECT_SERVER_SM_INIT * pSmInit = NULL; if ( this->IsConnected() ) { if ( m_wstrKey == aKey ) { DbgOut( WARN , DBG_DLL_INJECT_MGR , "Shared memory already connected. aKey=%ws" , aKey ); SetLastError( ERROR_ALREADY_EXISTS ); bRet = TRUE; } else { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "Shared memory already used by others. m_wstrKey=%ws, aKey=%ws" , m_wstrKey.c_str() , aKey ); SetLastError( ERROR_ADDRESS_ALREADY_ASSOCIATED ); } goto exit; } //Get all necessary handles and configuration from named share memory hSmInit = OpenFileMappingW( FILE_MAP_READ | FILE_MAP_WRITE , FALSE , aKey ); if ( ! hSmInit ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "OpenFileMappingW() with name %ws failed. GetLastError()=%!WINERROR!" , aKey , GetLastError() ); goto exit; } pSmInit = (DLL_INJECT_SERVER_SM_INIT *)MapViewOfFile( hSmInit , FILE_MAP_ALL_ACCESS , 0 , 0 , 0 ); if ( ! pSmInit ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "MapViewOfFile() with name %ws failed. GetLastError()=%!WINERROR!" , aKey , GetLastError() ); goto exit; } //Shared memory can be opened. Get data from shared memory first and then validate the content later m_wstrKey = aKey; CopyMemory( &m_SmInit , pSmInit , sizeof(m_SmInit) ); pSmInit->InitRsp.dwHookStatus = ERROR_APP_INIT_FAILURE; pSmInit->InitRsp.hModule = (UINT64)GetModuleHandleW( NULL ); //Validate Local handles if ( NULL == pSmInit->InitReq.Local.pLocalCtx || NULL == pSmInit->InitReq.Local.hRemoteProc || NULL == pSmInit->InitReq.Local.pfnFreeLibrary ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Local data are invalid" ); goto exit; } //Validate Remote handles if ( NULL == pSmInit->InitReq.Remote.hEvtInitRsp || NULL == pSmInit->InitReq.Remote.hDllInjectMgrAliveThread ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Remote data are invalid" ); goto exit; } for ( size_t i = 0 ; i < _countof( pSmInit->InitReq.Remote.hPerServerSm ) ; i++ ) { if ( NULL == pSmInit->InitReq.Remote.hPerServerSm[i] ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Remote.hPerServerSm are invalid" ); goto exit; } } for ( size_t i = 0 ; i < _countof( pSmInit->InitReq.Remote.hPerServerMutex ) ; i++ ) { if ( NULL == pSmInit->InitReq.Remote.hPerServerMutex[i] ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Remote.hPerServerMutex are invalid" ); goto exit; } } for ( size_t i = 0 ; i < _countof( pSmInit->InitReq.Remote.hPerServerEvt ) ; i++ ) { if ( NULL == pSmInit->InitReq.Remote.hPerServerEvt[i] ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Remote.hPerServerEvt are invalid" ); goto exit; } } for ( size_t i = 0 ; i < _countof( pSmInit->InitReq.Remote.hPerClientEvt ) ; i++ ) { if ( NULL == pSmInit->InitReq.Remote.hPerClientEvt[i] ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "InitReq.Remote.hPerClientEvt are invalid" ); goto exit; } } //Get shared memory used to exchange data m_SmData[PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL] = (PDLL_INJECT_SERVER_SM_DATA_HEADER)MapViewOfFile( (HANDLE)pSmInit->InitReq.Remote.hPerServerSm[PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL] , FILE_MAP_ALL_ACCESS , 0 , 0 , 0 ); if ( NULL == m_SmData[PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL] ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "MapViewOfFile() with PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL failed. GetLastError()=%!WINERROR!" , GetLastError() ); pSmInit->InitRsp.dwHookStatus = GetLastError(); goto exit; } m_SmData[PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE] = (PDLL_INJECT_SERVER_SM_DATA_HEADER)MapViewOfFile( (HANDLE)pSmInit->InitReq.Remote.hPerServerSm[PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE] , FILE_MAP_ALL_ACCESS , 0 , 0 , 0 ); if ( NULL == m_SmData[PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE] ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "MapViewOfFile() with PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE failed. GetLastError()=%!WINERROR!" , GetLastError() ); pSmInit->InitRsp.dwHookStatus = GetLastError(); goto exit; } DbgOut( VERB , DBG_DLL_INJECT_MGR , "Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_STOP]=0x%p, Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_REQ_OK]=0x%p, Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_RSP]=0x%p" , (HANDLE)pSmInit->InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_STOP] , (HANDLE)pSmInit->InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_REQ_OK] , (HANDLE)pSmInit->InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_RSP] ); pSmInit->InitRsp.dwHookStatus = ( aInitCbk ) ? aInitCbk( pSmInit->InitReq.wzServerDirPath , pSmInit->InitReq.wzClientCfgPath ) : ERROR_SUCCESS; if ( ERROR_SUCCESS == pSmInit->InitRsp.dwHookStatus ) { ATOMIC_ASSIGN( m_bConnected , TRUE ); bRet = TRUE; } exit : if ( pSmInit && pSmInit->InitReq.Remote.hEvtInitRsp ) { SetEvent( (HANDLE)pSmInit->InitReq.Remote.hEvtInitRsp ); CloseHandle( (HANDLE)pSmInit->InitReq.Remote.hEvtInitRsp ); pSmInit->InitReq.Remote.hEvtInitRsp = NULL; m_SmInit.InitReq.Remote.hEvtInitRsp = NULL; } if ( pSmInit && FALSE == UnmapViewOfFile( pSmInit ) ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "UnmapViewOfFile() pSmInit failed. GetLastError()=%!WINERROR!" , GetLastError() ); } if ( hSmInit && FALSE == CloseHandle( hSmInit ) ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "CloseHandle() hSmInit failed. GetLastError()=%!WINERROR!" , GetLastError() ); } if ( FALSE == bRet ) { this->Disconnect(); } return bRet; }
APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m, const char *file, apr_pool_t *pool) { HANDLE hMap; void *mapkey; void *base; if (!file) { return APR_EINVAL; } else { /* res_name_from_filename turns file into a pseudo-name * without slashes or backslashes, and prepends the \global * prefix on Win2K and later */ mapkey = res_name_from_filename(file, 1, pool); } #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { #ifndef _WIN32_WCE hMap = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, mapkey); #else /* The WCE 3.0 lacks OpenFileMapping. So we emulate one with * opening the existing shmem and reading its size from the header */ hMap = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(apr_shm_t), mapkey); #endif } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { hMap = OpenFileMappingA(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, mapkey); } #endif if (!hMap) { return apr_get_os_error(); } base = MapViewOfFile(hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (!base) { CloseHandle(hMap); return apr_get_os_error(); } *m = (apr_shm_t *) apr_palloc(pool, sizeof(apr_shm_t)); (*m)->pool = pool; (*m)->memblk = base; /* Real (*m)->mem->size could be recovered with VirtualQuery */ (*m)->size = (*m)->memblk->size; #if _WIN32_WCE /* Reopen with real size */ UnmapViewOfFile(base); CloseHandle(hMap); hMap = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, (*m)->size, mapkey); if (!hMap) { return apr_get_os_error(); } base = MapViewOfFile(hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (!base) { CloseHandle(hMap); return apr_get_os_error(); } #endif (*m)->hMap = hMap; (*m)->length = (*m)->memblk->length; (*m)->usrmem = (char*)base + sizeof(memblock_t); (*m)->filename = NULL; apr_pool_cleanup_register((*m)->pool, *m, shm_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; }
/*********************************************************************** * OutputDebugStringA (KERNEL32.@) * * Output by an application of an ascii string to a debugger (if attached) * and program log. * * PARAMS * str [I] The message to be logged and given to the debugger. * * RETURNS * * Nothing. */ void WINAPI OutputDebugStringA( LPCSTR str ) { static HANDLE DBWinMutex = NULL; static BOOL mutex_inited = FALSE; BOOL caught_by_dbg = TRUE; if (!str) str = ""; WARN("%s\n", debugstr_a(str)); /* raise exception, WaitForDebugEvent() will generate a corresponding debug event */ __TRY { ULONG_PTR args[2]; args[0] = strlen(str) + 1; args[1] = (ULONG_PTR)str; RaiseException( DBG_PRINTEXCEPTION_C, 0, 2, args ); } __EXCEPT(debug_exception_handler) { caught_by_dbg = FALSE; } __ENDTRY if (caught_by_dbg) return; /* send string to a system-wide monitor */ if (!mutex_inited) { /* first call to OutputDebugString, initialize mutex handle */ static const WCHAR mutexname[] = {'D','B','W','i','n','M','u','t','e','x',0}; HANDLE mutex = CreateMutexExW( NULL, mutexname, 0, SYNCHRONIZE ); if (mutex) { if (InterlockedCompareExchangePointer( &DBWinMutex, mutex, 0 ) != 0) { /* someone beat us here... */ CloseHandle( mutex ); } } mutex_inited = TRUE; } if (DBWinMutex) { static const WCHAR shmname[] = {'D','B','W','I','N','_','B','U','F','F','E','R',0}; static const WCHAR eventbuffername[] = {'D','B','W','I','N','_','B','U','F','F','E','R','_','R','E','A','D','Y',0}; static const WCHAR eventdataname[] = {'D','B','W','I','N','_','D','A','T','A','_','R','E','A','D','Y',0}; HANDLE mapping; mapping = OpenFileMappingW( FILE_MAP_WRITE, FALSE, shmname ); if (mapping) { LPVOID buffer; HANDLE eventbuffer, eventdata; buffer = MapViewOfFile( mapping, FILE_MAP_WRITE, 0, 0, 0 ); eventbuffer = OpenEventW( SYNCHRONIZE, FALSE, eventbuffername ); eventdata = OpenEventW( EVENT_MODIFY_STATE, FALSE, eventdataname ); if (buffer && eventbuffer && eventdata) { /* monitor is present, synchronize with other OutputDebugString invocations */ WaitForSingleObject( DBWinMutex, INFINITE ); /* acquire control over the buffer */ if (WaitForSingleObject( eventbuffer, 10000 ) == WAIT_OBJECT_0) { int str_len; struct _mon_buffer_t { DWORD pid; char buffer[1]; } *mon_buffer = (struct _mon_buffer_t*) buffer; str_len = strlen( str ); if (str_len > (4096 - sizeof(DWORD) - 1)) str_len = 4096 - sizeof(DWORD) - 1; mon_buffer->pid = GetCurrentProcessId(); memcpy( mon_buffer->buffer, str, str_len ); mon_buffer->buffer[str_len] = 0; /* signal data ready */ SetEvent( eventdata ); } ReleaseMutex( DBWinMutex ); } if (buffer) UnmapViewOfFile( buffer ); if (eventbuffer) CloseHandle( eventbuffer ); if (eventdata) CloseHandle( eventdata ); CloseHandle( mapping ); } } }
int main(int argc, char *argv[]) { HANDLE map; bool srvr = true; if (argc > 1 && !strcmp(argv[1], "client")) { srvr = false; } HANDLE ev; /* create event */ if (srvr) { ev = CreateEventW(NULL, false, false, SHM_EVENT); } else { ev = OpenEventW(EVENT_ALL_ACCESS, false, SHM_EVENT); } if (ev == NULL) { printf("can't create/open event"); exit(1); } HANDLE mutex; if (srvr) { mutex = CreateMutex(NULL, false, SHM_MUTEX); } else { mutex = OpenMutex(SYNCHRONIZE, false, SHM_MUTEX); } if (mutex == NULL) { printf("mutex error\n"); exit(1); } /* Shared memory */ if (srvr) { map = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4096, SHM_NAME); } else { map = OpenFileMappingW(FILE_MAP_ALL_ACCESS, false, SHM_NAME); } if (map == NULL) { fprintf(stderr, "Can't get file mapping: %lu\n", GetLastError()); exit(1); } void *mem; mem = MapViewOfFile(map, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (!mem) { fprintf(stderr, "MapViewOfFile() failed with %lu\n", GetLastError()); exit(2); } CloseHandle(map); struct my_mem *mm; mm = (struct my_mem *)mem; if (srvr == false) { /* writer */ printf("client\n"); mm->total = 4096; while(1) { int x = getchar(); WaitForSingleObject(mutex, INFINITE); printf("idx(%d) < total(%d)\n", mm->idx, mm->total); if (mm->idx < mm->total) { mm->arr[mm->idx] = x; mm->idx++; } SetEvent(ev); ReleaseMutex(mutex); /* end of file */ if (x < 0) break; } } else { /* reader */ while(1) { WaitForSingleObject(ev, INFINITE); WaitForSingleObject(mutex, INFINITE); int i; bool stop = false; for (i=0; i<mm->idx; i++) { if (mm->arr[i] < 0) stop = true; printf("%c", mm->arr[i]); } mm->idx = 0; ReleaseMutex(mutex); if (stop) break; } } UnmapViewOfFile(mem); CloseHandle(ev); CloseHandle(mutex); system("pause"); return 0; }
bool InitializeProfAPISharedObj() { gCAProfAPISharedMapFile = OpenFileMappingW(FILE_MAP_ALL_ACCESS, // read/write access FALSE, // do not inherit the name CPU_PROF_SHARED_OBJ); // name of mapping object if (!gCAProfAPISharedMapFile) { SECURITY_ATTRIBUTES secAttr; char secDesc[ SECURITY_DESCRIPTOR_MIN_LENGTH ]; secAttr.nLength = sizeof(secAttr); secAttr.bInheritHandle = FALSE; secAttr.lpSecurityDescriptor = &secDesc; bool bHasSD = false; OSVERSIONINFO osVersionInfo; osVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (GetVersionEx(&osVersionInfo)) { if (osVersionInfo.dwMajorVersion >= 6) { // Vista, Longhorn or later; bHasSD = true; } } if (bHasSD) { PSECURITY_DESCRIPTOR pSD; PACL pSacl = nullptr; // not allocated BOOL fSaclPresent = FALSE; BOOL fSaclDefaulted = FALSE; ConvertStringSecurityDescriptorToSecurityDescriptorW(L"S:(ML;;NW;;;LW)", // this means "low integrity" SDDL_REVISION_1, &pSD, nullptr); GetSecurityDescriptorSacl(pSD, &fSaclPresent, &pSacl, &fSaclDefaulted); SetSecurityDescriptorSacl(secAttr.lpSecurityDescriptor, TRUE, pSacl, FALSE); } InitializeSecurityDescriptor(secAttr.lpSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(secAttr.lpSecurityDescriptor, TRUE, 0, FALSE); gCAProfAPISharedMapFile = CreateFileMappingW(INVALID_HANDLE_VALUE, &secAttr, // default security PAGE_READWRITE, // read/write access 0, // max. object size CPU_PROF_SHARED_MEM_SIZE, // buffer size CPU_PROF_SHARED_OBJ); // name of mapping object } if (gCAProfAPISharedMapFile) { return true; } else { return false; } }
/*********************************************************************** * OutputDebugStringA (KERNEL32.@) * * Output by an application of an ascii string to a debugger (if attached) * and program log. * * PARAMS * str [I] The message to be logged and given to the debugger. * * RETURNS * * Nothing. */ void WINAPI OutputDebugStringA( LPCSTR str ) { static HANDLE DBWinMutex = NULL; static BOOL mutex_inited = FALSE; if (!str) str = ""; /* send string to attached debugger */ SERVER_START_REQ( output_debug_string ) { req->string = wine_server_client_ptr( str ); req->length = strlen(str) + 1; wine_server_call( req ); } SERVER_END_REQ; WARN("%s\n", debugstr_a(str)); /* send string to a system-wide monitor */ /* FIXME should only send to monitor if no debuggers are attached */ if (!mutex_inited) { /* first call to OutputDebugString, initialize mutex handle */ static const WCHAR mutexname[] = {'D','B','W','i','n','M','u','t','e','x',0}; HANDLE mutex = CreateMutexExW( NULL, mutexname, 0, SYNCHRONIZE ); if (mutex) { if (InterlockedCompareExchangePointer( &DBWinMutex, mutex, 0 ) != 0) { /* someone beat us here... */ CloseHandle( mutex ); } } mutex_inited = TRUE; } if (DBWinMutex) { static const WCHAR shmname[] = {'D','B','W','I','N','_','B','U','F','F','E','R',0}; static const WCHAR eventbuffername[] = {'D','B','W','I','N','_','B','U','F','F','E','R','_','R','E','A','D','Y',0}; static const WCHAR eventdataname[] = {'D','B','W','I','N','_','D','A','T','A','_','R','E','A','D','Y',0}; HANDLE mapping; mapping = OpenFileMappingW( FILE_MAP_WRITE, FALSE, shmname ); if (mapping) { LPVOID buffer; HANDLE eventbuffer, eventdata; buffer = MapViewOfFile( mapping, FILE_MAP_WRITE, 0, 0, 0 ); eventbuffer = OpenEventW( SYNCHRONIZE, FALSE, eventbuffername ); eventdata = OpenEventW( EVENT_MODIFY_STATE, FALSE, eventdataname ); if (buffer && eventbuffer && eventdata) { /* monitor is present, synchronize with other OutputDebugString invocations */ WaitForSingleObject( DBWinMutex, INFINITE ); /* acquire control over the buffer */ if (WaitForSingleObject( eventbuffer, 10000 ) == WAIT_OBJECT_0) { int str_len; struct _mon_buffer_t { DWORD pid; char buffer[1]; } *mon_buffer = (struct _mon_buffer_t*) buffer; str_len = strlen( str ); if (str_len > (4096 - sizeof(DWORD) - 1)) str_len = 4096 - sizeof(DWORD) - 1; mon_buffer->pid = GetCurrentProcessId(); memcpy( mon_buffer->buffer, str, str_len ); mon_buffer->buffer[str_len] = 0; /* signal data ready */ SetEvent( eventdata ); } ReleaseMutex( DBWinMutex ); } if (buffer) UnmapViewOfFile( buffer ); if (eventbuffer) CloseHandle( eventbuffer ); if (eventdata) CloseHandle( eventdata ); CloseHandle( mapping ); } } }
void MumbleManager::init() { #if defined BSD4_4 return; #endif if (mLinkedMem || !config.getBoolValue("enableMumble")) return; logger->log1("MumbleManager::init"); #ifdef WIN32 HANDLE hMapObject = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, L"MumbleLink"); if (!hMapObject) { logger->log1("MumbleManager::init can't open MumbleLink"); return; } mLinkedMem = reinterpret_cast<LinkedMem *>(MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(LinkedMem))); if (!mLinkedMem) { CloseHandle(hMapObject); hMapObject = nullptr; logger->log1("MumbleManager::init can't map MumbleLink"); return; } #elif defined BSD4_4 #else char memName[256]; snprintf(memName, sizeof(memName), "/MumbleLink.%u", getuid()); const int shmfd = shm_open(memName, O_RDWR, S_IRUSR | S_IWUSR); if (shmfd < 0) { logger->log1("MumbleManager::init can't" " open shared memory MumbleLink"); return; } mLinkedMem = static_cast<LinkedMem *>(mmap(nullptr, sizeof(struct LinkedMem), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0)); if (mLinkedMem == reinterpret_cast<void *>(-1)) { mLinkedMem = nullptr; logger->log1("MumbleManager::init can't map MumbleLink"); return; } #endif wcsncpy(mLinkedMemCache.name, L"ManaPlus", 256); wcsncpy(mLinkedMemCache.description, L"ManaPlus Plugin", 2048); mLinkedMemCache.uiVersion = 2; // Left handed coordinate system. // X positive towards "left". // Y positive towards "up". // Z positive towards "into screen". // // 1 unit = 1 meter // Unit vector pointing out of the avatars eyes // (here Front looks into scene). /* no way to look "up", 2d */ mLinkedMemCache.fAvatarFront[1] = 0.0F; // Unit vector pointing out of the top of the avatars head // (here Top looks straight up). /* no way to change this in tmw */ mLinkedMemCache.fAvatarTop[0] = 0.0F; mLinkedMemCache.fAvatarTop[1] = 1.0F; mLinkedMemCache.fAvatarTop[2] = 0.0F; mLinkedMemCache.fCameraFront[0] = 0.0F; mLinkedMemCache.fCameraFront[1] = 0.0F; mLinkedMemCache.fCameraFront[2] = 1.0F; mLinkedMemCache.fCameraTop[0] = 0.0F; mLinkedMemCache.fCameraTop[1] = 1.0F; mLinkedMemCache.fCameraTop[2] = 0.0F; mLinkedMemCache.uiTick++; }