//内核配置 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=QUERY_OBJECT_PTR_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(QUERY_OBJECT_PTR_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=QUERY_ME_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; }
int main (int argc, char *argv[]) { if (argc != 5) { fputs("Usage: lab1 [enc|dec] <input file> <output file> <key>", stderr); return -1; } enum mode mod; if (strncmp(argv[1], "enc", 3) == 0) { mod = ENC; } else if (strncmp(argv[1], "dec", 3) == 0) { mod = DEC; } else { fprintf(stderr, "Wrong encryption mode: \"%s\".", argv[1]); return -1; } HANDLE inf = 0; HANDLE inmmf = 0; PBYTE indata = NULL; HANDLE outf = 0; HANDLE outmmf = 0; PBYTE outdata = NULL; LARGE_INTEGER insz = {.QuadPart = 0}; LARGE_INTEGER outsz = {.QuadPart = 0}; unsigned char err = 1; inf = CreateFileA(argv[2], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); //printf("%0.16lx || %lu %s\n", inf, GetLastError(), argv[2]); inmmf = CreateFileMappingA(inf, NULL, PAGE_READONLY, 0, 0, NULL); if (inmmf == NULL) { fprintf(stderr, "Can't open memory mapped file. Error code: %lu\n", GetLastError()); goto err; } indata = (PBYTE)MapViewOfFile(inmmf, FILE_MAP_READ, 0, 0, 0); if (indata == NULL) { fprintf(stderr, "Can't map view of file. Error code: %lu\n", GetLastError()); goto err; } GetFileSizeEx(inf, &insz); outsz.QuadPart = (insz.QuadPart / 8 + 2) * 8; outf = CreateFileA(argv[3], GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); outmmf = CreateFileMappingA(outf, NULL, PAGE_READWRITE, outsz.HighPart, outsz.LowPart, NULL); if (outmmf == NULL) { fprintf(stderr, "Can't open memory mapped file. Error code: %lu\n", GetLastError()); goto err; } outdata = (PBYTE)MapViewOfFile(outmmf, FILE_MAP_WRITE, 0, 0, 0); if (outdata == NULL) { fprintf(stderr, "Can't map view of file. Error code: %lu\n", GetLastError()); goto err; } // Crypto stuff BOOL res; HCRYPTPROV prov; if (!CryptAcquireContext(&prov, 0, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { fputs("Cannot acquire crypt context.", stderr); goto err; } HCRYPTKEY key = generateKey(prov, CALG_3DES, argv[4]); crash_if(key == 0, "Cannot make a key."); for (LARGE_INTEGER i = {.QuadPart = 0}; i.QuadPart < insz.QuadPart; (i.QuadPart) += buf_size) { unsigned char buf[buf_size + block_size]; DWORD len = buf_size; void *inp = indata + i.QuadPart, *outp = outdata + i.QuadPart; BOOL final = insz.QuadPart - i.QuadPart <= buf_size; if (final) { len = insz.QuadPart - i.QuadPart; } memcpy(buf, inp, len); if (mod == ENC) { res = CryptEncrypt(key, 0, final, 0, buf, &len, buf_size + block_size); } else { res = CryptDecrypt(key, 0, final, 0, buf, &len); } if (res) { memcpy(outp, buf, len); if (final) { outsz.QuadPart = i.QuadPart + len; } } else { fprintf(stderr, "Can't crypt the block 0x%lx. Error code: %lu\n", i.QuadPart, GetLastError()); goto err; } } CryptDestroyKey(key); CryptReleaseContext(prov,0); err = 0; err: // Freeing resources. apply_not_null(indata, UnmapViewOfFile); apply_not_null(inmmf, CloseHandle); apply_not_null(inf, CloseHandle); apply_not_null(outdata, UnmapViewOfFile); apply_not_null(outmmf, CloseHandle); if (outf) { SetFilePointer(outf, outsz.LowPart, &(outsz.HighPart), FILE_BEGIN); SetEndOfFile(outf); } apply_not_null(outf, CloseHandle); if (err) return -1; else return 0; }
template <typename PointT> int pcl::PCDWriter::writeBinaryCompressed (const std::string &file_name, const pcl::PointCloud<PointT> &cloud) { if (cloud.points.empty ()) { throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Input point cloud has no data!"); return (-1); } int data_idx = 0; std::ostringstream oss; oss << generateHeader<PointT> (cloud) << "DATA binary_compressed\n"; oss.flush (); data_idx = static_cast<int> (oss.tellp ()); #if _WIN32 HANDLE h_native_file = CreateFileA (file_name.c_str (), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (h_native_file == INVALID_HANDLE_VALUE) { throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during CreateFile!"); return (-1); } #else int fd = pcl_open (file_name.c_str (), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd < 0) { throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during open!"); return (-1); } #endif // Mandatory lock file boost::interprocess::file_lock file_lock; setLockingPermissions (file_name, file_lock); std::vector<pcl::PCLPointField> fields; size_t fsize = 0; size_t data_size = 0; size_t nri = 0; pcl::getFields (cloud, fields); std::vector<int> fields_sizes (fields.size ()); // Compute the total size of the fields for (size_t i = 0; i < fields.size (); ++i) { if (fields[i].name == "_") continue; fields_sizes[nri] = fields[i].count * pcl::getFieldSize (fields[i].datatype); fsize += fields_sizes[nri]; fields[nri] = fields[i]; ++nri; } fields_sizes.resize (nri); fields.resize (nri); // Compute the size of data data_size = cloud.points.size () * fsize; ////////////////////////////////////////////////////////////////////// // Empty array holding only the valid data // data_size = nr_points * point_size // = nr_points * (sizeof_field_1 + sizeof_field_2 + ... sizeof_field_n) // = sizeof_field_1 * nr_points + sizeof_field_2 * nr_points + ... sizeof_field_n * nr_points char *only_valid_data = static_cast<char*> (malloc (data_size)); // Convert the XYZRGBXYZRGB structure to XXYYZZRGBRGB to aid compression. For // this, we need a vector of fields.size () (4 in this case), which points to // each individual plane: // pters[0] = &only_valid_data[offset_of_plane_x]; // pters[1] = &only_valid_data[offset_of_plane_y]; // pters[2] = &only_valid_data[offset_of_plane_z]; // pters[3] = &only_valid_data[offset_of_plane_RGB]; // std::vector<char*> pters (fields.size ()); int toff = 0; for (size_t i = 0; i < pters.size (); ++i) { pters[i] = &only_valid_data[toff]; toff += fields_sizes[i] * static_cast<int> (cloud.points.size ()); } // Go over all the points, and copy the data in the appropriate places for (size_t i = 0; i < cloud.points.size (); ++i) { for (size_t j = 0; j < fields.size (); ++j) { memcpy (pters[j], reinterpret_cast<const char*> (&cloud.points[i]) + fields[j].offset, fields_sizes[j]); // Increment the pointer pters[j] += fields_sizes[j]; } } char* temp_buf = static_cast<char*> (malloc (static_cast<size_t> (static_cast<float> (data_size) * 1.5f + 8.0f))); // Compress the valid data unsigned int compressed_size = pcl::lzfCompress (only_valid_data, static_cast<uint32_t> (data_size), &temp_buf[8], static_cast<uint32_t> (static_cast<float>(data_size) * 1.5f)); unsigned int compressed_final_size = 0; // Was the compression successful? if (compressed_size) { char *header = &temp_buf[0]; memcpy (&header[0], &compressed_size, sizeof (unsigned int)); memcpy (&header[4], &data_size, sizeof (unsigned int)); data_size = compressed_size + 8; compressed_final_size = static_cast<uint32_t> (data_size) + data_idx; } else { #if !_WIN32 pcl_close (fd); #endif resetLockingPermissions (file_name, file_lock); throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during compression!"); return (-1); } #if !_WIN32 // Stretch the file size to the size of the data off_t result = pcl_lseek (fd, getpagesize () + data_size - 1, SEEK_SET); if (result < 0) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); PCL_ERROR ("[pcl::PCDWriter::writeBinary] lseek errno: %d strerror: %s\n", errno, strerror (errno)); throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during lseek ()!"); return (-1); } // Write a bogus entry so that the new file size comes in effect result = static_cast<int> (::write (fd, "", 1)); if (result != 1) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during write ()!"); return (-1); } #endif // Prepare the map #if _WIN32 HANDLE fm = CreateFileMapping (h_native_file, NULL, PAGE_READWRITE, 0, compressed_final_size, NULL); char *map = static_cast<char*>(MapViewOfFile (fm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, compressed_final_size)); CloseHandle (fm); #else char *map = static_cast<char*> (mmap (0, compressed_final_size, PROT_WRITE, MAP_SHARED, fd, 0)); if (map == reinterpret_cast<char*> (-1)) //MAP_FAILED) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during mmap ()!"); return (-1); } #endif // Copy the header memcpy (&map[0], oss.str ().c_str (), data_idx); // Copy the compressed data memcpy (&map[data_idx], temp_buf, data_size); #if !_WIN32 // If the user set the synchronization flag on, call msync if (map_synchronization_) msync (map, compressed_final_size, MS_SYNC); #endif // Unmap the pages of memory #if _WIN32 UnmapViewOfFile (map); #else if (munmap (map, (compressed_final_size)) == -1) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during munmap ()!"); return (-1); } #endif // Close file #if _WIN32 CloseHandle (h_native_file); #else pcl_close (fd); #endif resetLockingPermissions (file_name, file_lock); free (only_valid_data); free (temp_buf); return (0); }
template <typename PointT> int pcl::PCDWriter::writeBinary (const std::string &file_name, const pcl::PointCloud<PointT> &cloud, const std::vector<int> &indices) { if (cloud.points.empty () || indices.empty ()) { throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Input point cloud has no data or empty indices given!"); return (-1); } int data_idx = 0; std::ostringstream oss; oss << generateHeader<PointT> (cloud, static_cast<int> (indices.size ())) << "DATA binary\n"; oss.flush (); data_idx = static_cast<int> (oss.tellp ()); #if _WIN32 HANDLE h_native_file = CreateFileA (file_name.c_str (), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (h_native_file == INVALID_HANDLE_VALUE) { throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during CreateFile!"); return (-1); } #else int fd = pcl_open (file_name.c_str (), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd < 0) { throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during open!"); return (-1); } #endif // Mandatory lock file boost::interprocess::file_lock file_lock; setLockingPermissions (file_name, file_lock); std::vector<pcl::PCLPointField> fields; std::vector<int> fields_sizes; size_t fsize = 0; size_t data_size = 0; size_t nri = 0; pcl::getFields (cloud, fields); // Compute the total size of the fields for (size_t i = 0; i < fields.size (); ++i) { if (fields[i].name == "_") continue; int fs = fields[i].count * getFieldSize (fields[i].datatype); fsize += fs; fields_sizes.push_back (fs); fields[nri++] = fields[i]; } fields.resize (nri); data_size = indices.size () * fsize; // Prepare the map #if _WIN32 HANDLE fm = CreateFileMapping (h_native_file, NULL, PAGE_READWRITE, 0, data_idx + data_size, NULL); char *map = static_cast<char*>(MapViewOfFile (fm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, data_idx + data_size)); CloseHandle (fm); #else // Stretch the file size to the size of the data off_t result = pcl_lseek (fd, getpagesize () + data_size - 1, SEEK_SET); if (result < 0) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); PCL_ERROR ("[pcl::PCDWriter::writeBinary] lseek errno: %d strerror: %s\n", errno, strerror (errno)); throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during lseek ()!"); return (-1); } // Write a bogus entry so that the new file size comes in effect result = static_cast<int> (::write (fd, "", 1)); if (result != 1) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during write ()!"); return (-1); } char *map = static_cast<char*> (mmap (0, data_idx + data_size, PROT_WRITE, MAP_SHARED, fd, 0)); if (map == reinterpret_cast<char*> (-1)) //MAP_FAILED) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during mmap ()!"); return (-1); } #endif // Copy the header memcpy (&map[0], oss.str ().c_str (), data_idx); char *out = &map[0] + data_idx; // Copy the data for (size_t i = 0; i < indices.size (); ++i) { int nrj = 0; for (size_t j = 0; j < fields.size (); ++j) { memcpy (out, reinterpret_cast<const char*> (&cloud.points[indices[i]]) + fields[j].offset, fields_sizes[nrj]); out += fields_sizes[nrj++]; } } #if !_WIN32 // If the user set the synchronization flag on, call msync if (map_synchronization_) msync (map, data_idx + data_size, MS_SYNC); #endif // Unmap the pages of memory #if _WIN32 UnmapViewOfFile (map); #else if (munmap (map, (data_idx + data_size)) == -1) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during munmap ()!"); return (-1); } #endif // Close file #if _WIN32 CloseHandle(h_native_file); #else pcl_close (fd); #endif resetLockingPermissions (file_name, file_lock); return (0); }
int stream_open(stream *f, buffer *fn) { //打开文件并map到内存(起始地址和内存长度存储在stream结构体参数f内),出错返回-1; struct stat st; #ifdef HAVE_MMAP int fd; #elif defined __WIN32 HANDLE *fh, *mh; void *p; #endif f->start = NULL; if (-1 == stat(fn->ptr, &st)) { //获取指定文件属性 return -1; } f->size = st.st_size; #ifdef HAVE_MMAP if (-1 == (fd = open(fn->ptr, O_RDONLY | O_BINARY))) { return -1; } f->start = mmap(0, f->size, PROT_READ, MAP_SHARED, fd, 0); //映射 close(fd); //关闭文件 if (MAP_FAILED == f->start) { //映射失败 return -1; } #elif defined __WIN32 //windows环境 fh = CreateFile(fn->ptr, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL); if (!fh) return -1; mh = CreateFileMapping( fh, NULL, PAGE_READONLY, (sizeof(off_t) > 4) ? f->size >> 32 : 0, f->size & 0xffffffff, NULL); if (!mh) { /* LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); */ return -1; } p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, 0); CloseHandle(mh); CloseHandle(fh); f->start = p; #else # error no mmap found #endif return 0; }
HMODULE WINAPI MonoLoadImage(LPCWSTR FileName) { HANDLE FileHandle; DWORD FileSize; HANDLE MapHandle; IMAGE_DOS_HEADER* DosHeader; IMAGE_NT_HEADERS32* NtHeaders32; #ifdef _WIN64 IMAGE_NT_HEADERS64* NtHeaders64; #endif HMODULE ModuleHandle; FileHandle = CreateFile(FileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (FileHandle == INVALID_HANDLE_VALUE) return NULL; FileSize = GetFileSize(FileHandle, NULL); if (FileSize == INVALID_FILE_SIZE) goto CloseFile; MapHandle = CreateFileMapping(FileHandle, NULL, PAGE_READONLY, 0, 0, NULL); if (MapHandle == NULL) goto CloseFile; DosHeader = (IMAGE_DOS_HEADER*)MapViewOfFile(MapHandle, FILE_MAP_READ, 0, 0, 0); if (DosHeader == NULL) goto CloseMap; if (FileSize < sizeof(IMAGE_DOS_HEADER) || DosHeader->e_magic != IMAGE_DOS_SIGNATURE || FileSize < DosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS32)) goto InvalidImageFormat; NtHeaders32 = (IMAGE_NT_HEADERS32*)((DWORD_PTR)DosHeader + DosHeader->e_lfanew); if (NtHeaders32->Signature != IMAGE_NT_SIGNATURE) goto InvalidImageFormat; #ifdef _WIN64 NtHeaders64 = (IMAGE_NT_HEADERS64*)NtHeaders32; if (NtHeaders64->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) { if (FileSize < DosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS64) || NtHeaders64->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR || !NtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress) goto InvalidImageFormat; goto ValidImage; } #endif if (NtHeaders32->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC || NtHeaders32->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR || !NtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress) { InvalidImageFormat: SetLastError(STATUS_INVALID_IMAGE_FORMAT); goto UnmapView; } #ifdef _WIN64 ValidImage: #endif UnmapViewOfFile(DosHeader); CloseHandle(MapHandle); ModuleHandle = LoadLibrary(FileName); CloseHandle(FileHandle); return ModuleHandle; UnmapView: UnmapViewOfFile(DosHeader); CloseMap: CloseHandle(MapHandle); CloseFile: CloseHandle(FileHandle); return NULL; }
GimpPlugInShm * gimp_plug_in_shm_new (void) { /* allocate a piece of shared memory for use in transporting tiles * to plug-ins. if we can't allocate a piece of shared memory then * we'll fall back on sending the data over the pipe. */ GimpPlugInShm *shm = g_slice_new0 (GimpPlugInShm); shm->shm_ID = -1; #if defined(USE_SYSV_SHM) /* Use SysV shared memory mechanisms for transferring tile data. */ { shm->shm_ID = shmget (IPC_PRIVATE, TILE_MAP_SIZE, IPC_CREAT | 0600); if (shm->shm_ID != -1) { shm->shm_addr = (guchar *) shmat (shm->shm_ID, NULL, 0); if (shm->shm_addr == (guchar *) -1) { g_printerr ("shmat() failed: %s\n" ERRMSG_SHM_DISABLE, g_strerror (errno)); shmctl (shm->shm_ID, IPC_RMID, NULL); shm->shm_ID = -1; } #ifdef IPC_RMID_DEFERRED_RELEASE if (shm->shm_addr != (guchar *) -1) shmctl (shm->shm_ID, IPC_RMID, NULL); #endif } else { g_printerr ("shmget() failed: %s\n" ERRMSG_SHM_DISABLE, g_strerror (errno)); } } #elif defined(USE_WIN32_SHM) /* Use Win32 shared memory mechanisms for transferring tile data. */ { gint pid; gchar fileMapName[MAX_PATH]; /* Our shared memory id will be our process ID */ pid = GetCurrentProcessId (); /* From the id, derive the file map name */ g_snprintf (fileMapName, sizeof (fileMapName), "GIMP%d.SHM", pid); /* Create the file mapping into paging space */ shm->shm_handle = CreateFileMapping (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, TILE_MAP_SIZE, fileMapName); if (shm->shm_handle) { /* Map the shared memory into our address space for use */ shm->shm_addr = (guchar *) MapViewOfFile (shm->shm_handle, FILE_MAP_ALL_ACCESS, 0, 0, TILE_MAP_SIZE); /* Verify that we mapped our view */ if (shm->shm_addr) { shm->shm_ID = pid; } else { g_printerr ("MapViewOfFile error: %d... " ERRMSG_SHM_DISABLE, GetLastError ()); } } else { g_printerr ("CreateFileMapping error: %d... " ERRMSG_SHM_DISABLE, GetLastError ()); } } #elif defined(USE_POSIX_SHM) /* Use POSIX shared memory mechanisms for transferring tile data. */ { gint pid; gchar shm_handle[32]; gint shm_fd; /* Our shared memory id will be our process ID */ pid = gimp_get_pid (); /* From the id, derive the file map name */ g_snprintf (shm_handle, sizeof (shm_handle), "/gimp-shm-%d", pid); /* Create the file mapping into paging space */ shm_fd = shm_open (shm_handle, O_RDWR | O_CREAT, 0600); if (shm_fd != -1) { if (ftruncate (shm_fd, TILE_MAP_SIZE) != -1) { /* Map the shared memory into our address space for use */ shm->shm_addr = (guchar *) mmap (NULL, TILE_MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); /* Verify that we mapped our view */ if (shm->shm_addr != MAP_FAILED) { shm->shm_ID = pid; } else { g_printerr ("mmap() failed: %s\n" ERRMSG_SHM_DISABLE, g_strerror (errno)); shm_unlink (shm_handle); } } else { g_printerr ("ftruncate() failed: %s\n" ERRMSG_SHM_DISABLE, g_strerror (errno)); shm_unlink (shm_handle); } close (shm_fd); } else { g_printerr ("shm_open() failed: %s\n" ERRMSG_SHM_DISABLE, g_strerror (errno)); } } #endif if (shm->shm_ID == -1) { g_slice_free (GimpPlugInShm, shm); shm = NULL; } else { GIMP_LOG (SHM, "attached shared memory segment ID = %d", shm->shm_ID); } return shm; }
void ExecScript(int log) { char szRet[128] = ""; char *pExec; int nComSpecSize; char meDLLPath[MAX_PATH]; char *p; char *executor; char *g_exec; unsigned int g_to; BOOL bOEM; nComSpecSize = GetModuleFileName(g_hInst, meDLLPath, MAX_PATH) + 2; // 2 chars for quotes p = meDLLPath + nComSpecSize - 2; // point p at null char of meDLLPath g_exec = (char *)GlobalAlloc(GPTR, sizeof(char)*g_stringsize+nComSpecSize+2); // 1 for space, 1 for null *g_exec = '"'; executor = g_exec + 1; do { if (*p == '\\') break; p = CharPrev(meDLLPath, p); } while (p > meDLLPath); if (p == meDLLPath) { // bad path pushstring("error"); GlobalFree(g_exec); return; } *p = 0; GetTempFileName(meDLLPath, "ns", 0, executor); *p = '\\'; if (CopyFile(meDLLPath, executor, FALSE)) { HANDLE hFile, hMapping; LPBYTE pMapView; PIMAGE_NT_HEADERS pNTHeaders; hFile = CreateFile(executor, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING,0, 0); hMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL); pMapView = MapViewOfFile(hMapping, FILE_MAP_WRITE, 0, 0, 0); if (pMapView) { pNTHeaders = (PIMAGE_NT_HEADERS)(pMapView + ((PIMAGE_DOS_HEADER)pMapView)->e_lfanew); pNTHeaders->FileHeader.Characteristics = IMAGE_FILE_32BIT_MACHINE | IMAGE_FILE_LOCAL_SYMS_STRIPPED | IMAGE_FILE_LINE_NUMS_STRIPPED | IMAGE_FILE_EXECUTABLE_IMAGE; pNTHeaders->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI; pNTHeaders->OptionalHeader.AddressOfEntryPoint = (DWORD)WinMain - (DWORD)g_hInst; UnmapViewOfFile(pMapView); } CloseHandle(hMapping); CloseHandle(hFile); } lstrcat(g_exec, "\""); g_to = 0; // default is no timeout bOEM = FALSE; // default is no OEM->ANSI conversion g_hwndList = NULL; if (g_hwndParent) g_hwndList = FindWindowEx(FindWindowEx(g_hwndParent,NULL,"#32770",NULL),NULL,"SysListView32",NULL); // add space pExec = g_exec + lstrlen(g_exec); *pExec = ' '; pExec++; params: popstring(pExec); if (my_strstr(pExec, "/TIMEOUT=") == pExec) { char *szTimeout = pExec + 9; g_to = my_atoi(szTimeout); *pExec = 0; goto params; } if (!lstrcmpi(pExec, "/OEM")) { bOEM = TRUE; *pExec = 0; goto params; } if (!pExec[0]) { pushstring("error"); *(pExec-2) = '\0'; // skip space and quote DeleteFile(executor); GlobalFree(g_exec); return; } { STARTUPINFO si={sizeof(si),}; SECURITY_ATTRIBUTES sa={sizeof(sa),}; SECURITY_DESCRIPTOR sd={0,}; PROCESS_INFORMATION pi={0,}; OSVERSIONINFO osv={sizeof(osv)}; HANDLE newstdout=0,read_stdout=0; HANDLE newstdin=0,read_stdin=0; DWORD dwRead = 1; DWORD dwExit = !STILL_ACTIVE; DWORD dwLastOutput; static char szBuf[1024]; HGLOBAL hUnusedBuf = NULL; char *szUnusedBuf = 0; if (log) { hUnusedBuf = GlobalAlloc(GHND, log & 2 ? g_stringsize : sizeof(szBuf)*4); if (!hUnusedBuf) { lstrcpy(szRet, "error"); goto done; } szUnusedBuf = (char *)GlobalLock(hUnusedBuf); } GetVersionEx(&osv); if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT) { InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd,true,NULL,false); sa.lpSecurityDescriptor = &sd; } else sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = true; if (!CreatePipe(&read_stdout,&newstdout,&sa,0)) { lstrcpy(szRet, "error"); goto done; } if (!CreatePipe(&read_stdin,&newstdin,&sa,0)) { lstrcpy(szRet, "error"); goto done; } GetStartupInfo(&si); si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdInput = newstdin; si.hStdOutput = newstdout; si.hStdError = newstdout; if (!CreateProcess(NULL,g_exec,NULL,NULL,TRUE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi)) { lstrcpy(szRet, "error"); goto done; } dwLastOutput = GetTickCount(); while (dwExit == STILL_ACTIVE || dwRead) { PeekNamedPipe(read_stdout, 0, 0, 0, &dwRead, NULL); if (dwRead) { dwLastOutput = GetTickCount(); ReadFile(read_stdout, szBuf, sizeof(szBuf)-1, &dwRead, NULL); szBuf[dwRead] = 0; if (log) { char *p, *p2; SIZE_T iReqLen = lstrlen(szBuf) + lstrlen(szUnusedBuf); if (GlobalSize(hUnusedBuf) < iReqLen && (iReqLen < g_stringsize || !(log & 2))) { GlobalUnlock(hUnusedBuf); hUnusedBuf = GlobalReAlloc(hUnusedBuf, iReqLen+sizeof(szBuf), GHND); if (!hUnusedBuf) { lstrcpy(szRet, "error"); break; } szUnusedBuf = (char *)GlobalLock(hUnusedBuf); } p = szUnusedBuf; // get the old left overs if (iReqLen < g_stringsize || !(log & 2)) lstrcat(p, szBuf); else { lstrcpyn(p + lstrlen(p), szBuf, g_stringsize - lstrlen(p)); } if (!(log & 2)) { while ((p = my_strstr(p, "\t"))) { if ((int)(p - szUnusedBuf) > (int)(GlobalSize(hUnusedBuf) - TAB_REPLACE_SIZE - 1)) { *p++ = ' '; } else { int len = lstrlen(p); char *c_out=(char*)p+TAB_REPLACE_SIZE+len; char *c_in=(char *)p+len; while (len-- > 0) { *c_out--=*c_in--; } lstrcpy(p, TAB_REPLACE); p += TAB_REPLACE_SIZE; *p = ' '; } } p = szUnusedBuf; // get the old left overs for (p2 = p; *p2;) { if (*p2 == '\r') { *p2++ = 0; continue; } if (*p2 == '\n') { *p2 = 0; while (!*p && p != p2) p++; LogMessage(p, bOEM); p = ++p2; continue; } p2 = CharNext(p2); } // If data was taken out from the unused buffer, move p contents to the start of szUnusedBuf if (p != szUnusedBuf) { char *p2 = szUnusedBuf; while (*p) *p2++ = *p++; *p2 = 0; } } } } else { if (g_to && GetTickCount() > dwLastOutput+g_to) { TerminateProcess(pi.hProcess, -1); lstrcpy(szRet, "timeout"); } else Sleep(LOOPTIMEOUT); } GetExitCodeProcess(pi.hProcess, &dwExit); if (dwExit != STILL_ACTIVE) { PeekNamedPipe(read_stdout, 0, 0, 0, &dwRead, NULL); } } done: if (log & 2) pushstring(szUnusedBuf); if (log & 1 && *szUnusedBuf) LogMessage(szUnusedBuf, bOEM); if ( dwExit == STATUS_ILLEGAL_INSTRUCTION ) lstrcpy(szRet, "error"); if (!szRet[0]) wsprintf(szRet,"%d",dwExit); pushstring(szRet); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(newstdout); CloseHandle(read_stdout); CloseHandle(newstdin); CloseHandle(read_stdin); *(pExec-2) = '\0'; // skip space and quote DeleteFile(executor); GlobalFree(g_exec); if (log) { GlobalUnlock(hUnusedBuf); GlobalFree(hUnusedBuf); } } }
/*** MapFile - Map existing file to memory address * * Entry: * pmmf - Pointer to structure to receive mapping information * psz - File name * fWrite - TRUE => read/write access, else read-only access * * Exit-Success: * Returns TRUE; pmmf filled in * * Exit-Failure: * Returns FALSE. */ BOOL MapFile(PMEMORYMAPPEDFILE pmmf, char *psz, BOOL fWrite) { ULONG ul; DWORD fdwAccess; DWORD fdwShareMode; DWORD fdwProtect; DWORD fdwAccessMapping; // Construct access settings if (fWrite) { fdwAccess = GENERIC_READ | GENERIC_WRITE; fdwShareMode = 0; // Do not permit any other access fdwProtect = PAGE_READWRITE; fdwAccessMapping = FILE_MAP_WRITE; } else { fdwAccess = GENERIC_READ; fdwShareMode = FILE_SHARE_READ; // Allow other readers fdwProtect = PAGE_READONLY; fdwAccessMapping = FILE_MAP_READ; } //** Clear structure, to simplify error path pmmf->pb = NULL; pmmf->cb = 0; pmmf->hfm = NULL; pmmf->hf = NULL; pmmf->ach[0] = '\0'; //** Open file pmmf->hf = CreateFile(psz, // file name fdwAccess, // r/w or read-only fdwShareMode, // allow nothing or allow reading NULL, // default security OPEN_EXISTING,// file must exist 0, // file attributes are don't care NULL); // no template file if (!pmmf->hf) { ul = GetLastError(); // Get last error Error("Cannot open file: %s", StringFromWin32ErrorCode(ul)); goto error; } //** Get file size pmmf->cb = GetFileSize(pmmf->hf, NULL) ; if (pmmf->cb == 0xFFFFFFFF) { ul = GetLastError(); //** Get error code Error("Cannot get file size: %s",StringFromWin32ErrorCode(ul)); goto error; } //** Create anonymous, read-only file mapping pmmf->hfm = CreateFileMapping(pmmf->hf,NULL,fdwProtect, 0,0, NULL); if (!pmmf->hfm) { ul = GetLastError(); //** Get error code Error("Cannot create file mapping: %s",StringFromWin32ErrorCode(ul)); goto error; } //** Map from beginning of file (0,0) for entire length of file (0) pmmf->pb = MapViewOfFile(pmmf->hfm,fdwAccessMapping, 0,0, 0); if (!pmmf->pb) { ul = GetLastError(); //** Get error code Error("Cannot map view of file: %s",StringFromWin32ErrorCode(ul)); goto error; } //** Save name in mmf structure strcpy(pmmf->ach,psz); //** Success return TRUE; error: //** Clean up mmf if (pmmf->hfm) { CloseHandle(pmmf->hfm); pmmf->hfm = NULL; } if (pmmf->hf) { CloseHandle(pmmf->hf); pmmf->hf = NULL; } pmmf->cb = 0; return FALSE; }
MMap::MMap (const Entry& entry, bool readwrite, bool preload, int64_t mapped_size) : Entry (entry), addr (NULL), first (NULL), msize (mapped_size), readwrite (readwrite) { DEBUG ("memory-mapping file \"" + Entry::name + "\"..."); struct stat sbuf; if (stat (Entry::name.c_str(), &sbuf)) throw Exception ("cannot stat file \"" + Entry::name + "\": " + strerror (errno)); mtime = sbuf.st_mtime; if (msize < 0) msize = sbuf.st_size - start; else if (start + msize > sbuf.st_size) throw Exception ("file \"" + Entry::name + "\" is smaller than expected"); bool delayed_writeback = false; if (readwrite) { #ifdef MRTRIX_WINDOWS const unsigned int length = 255; char root_path[length]; if (GetVolumePathName (Entry::name.c_str(), root_path, length)) { // Returns non-zero on success const unsigned int code = GetDriveType (root_path); switch (code) { case 0: // DRIVE_UNKNOWN DEBUG ("cannot get filesystem information on file \"" + Entry::name + "\": " + strerror (errno)); DEBUG (" defaulting to delayed write-back"); delayed_writeback = true; break; case 1: // DRIVE_NO_ROOT_DIR: DEBUG ("erroneous root path derived for file \"" + Entry::name + "\": " + strerror (errno)); DEBUG (" defaulting to delayed write-back"); delayed_writeback = true; break; case 2: // DRIVE_REMOVABLE DEBUG ("Drive for file \"" + Entry::name + "\" detected as removable; using memory-mapping"); break; case 3: // DRIVE_FIXED DEBUG ("Drive for file \"" + Entry::name + "\" detected as fixed; using memory-mapping"); break; case 4: // DRIVE_REMOTE DEBUG ("Drive for file \"" + Entry::name + "\" detected as network - using delayed write-back"); delayed_writeback = true; break; case 5: // DRIVE_CDROM DEBUG ("Drive for file \"" + Entry::name + "\" detected as CD-ROM - using delayed write-back"); delayed_writeback = true; break; case 6: // DRIVE_RAMDISK DEBUG ("Drive for file \"" + Entry::name + "\" detected as RAM - using memory-mapping"); break; } } else { DEBUG ("unable to query root drive path for file \"" + Entry::name + "\"; using delayed write-back"); delayed_writeback = true; } #else struct statfs fsbuf; if (statfs (Entry::name.c_str(), &fsbuf)) { DEBUG ("cannot get filesystem information on file \"" + Entry::name + "\": " + strerror (errno)); DEBUG (" defaulting to delayed write-back"); delayed_writeback = true; } if (fsbuf.f_type == 0xff534d42 /* CIFS */|| fsbuf.f_type == 0x6969 /* NFS */ || fsbuf.f_type == 0x65735546 /* FUSE */ || fsbuf.f_type == 0x517b /* SMB */ #ifdef MRTRIX_MACOSX || fsbuf.f_type == 0x0017 /* OSXFUSE */ #endif ) { DEBUG ("\"" + Entry::name + "\" appears to reside on a networked filesystem - using delayed write-back"); delayed_writeback = true; } #endif if (delayed_writeback) { try { first = new uint8_t [msize]; if (!first) throw 1; } catch (...) { throw Exception ("error allocating memory to hold mmap buffer contents"); } if (preload) { CONSOLE ("preloading contents of mapped file \"" + Entry::name + "\"..."); std::ifstream in (Entry::name.c_str(), std::ios::in | std::ios::binary); if (!in) throw Exception ("failed to open file \"" + Entry::name + "\": " + strerror (errno)); in.seekg (start, in.beg); in.read ((char*) first, msize); if (!in.good()) throw Exception ("error preloading contents of file \"" + Entry::name + "\": " + strerror(errno)); } else memset (first, 0, msize); DEBUG ("file \"" + Entry::name + "\" held in RAM at " + str ( (void*) first) + ", size " + str (msize)); return; } } // use regular memory-mapping: if ( (fd = open (Entry::name.c_str(), ( readwrite ? O_RDWR : O_RDONLY ), 0666)) < 0) throw Exception ("error opening file \"" + Entry::name + "\": " + strerror (errno)); try { #ifdef MRTRIX_WINDOWS HANDLE handle = CreateFileMapping ( (HANDLE) _get_osfhandle (fd), NULL, ( readwrite ? PAGE_READWRITE : PAGE_READONLY ), 0, start + msize, NULL); if (!handle) throw 0; addr = static_cast<uint8_t*> (MapViewOfFile (handle, ( readwrite ? FILE_MAP_ALL_ACCESS : FILE_MAP_READ ), 0, 0, start + msize)); if (!addr) throw 0; CloseHandle (handle); #else addr = static_cast<uint8_t*> (mmap ( (char*) 0, start + msize, ( readwrite ? PROT_WRITE | PROT_READ : PROT_READ ), MAP_SHARED, fd, 0)); if (addr == MAP_FAILED) throw 0; #endif } catch (...) { close (fd); addr = NULL; throw Exception ("memory-mapping failed for file \"" + Entry::name + "\": " + strerror (errno)); } first = addr + start; DEBUG ("file \"" + Entry::name + "\" mapped at " + str ( (void*) addr) + ", size " + str (msize) + " (read-" + (readwrite ? "write" : "only") + ")"); }
int __cdecl main(int argc, char *argv[]) { HANDLE FileMappingHandle; HANDLE OpenFileMappingHandle; HANDLE lpMapViewAddress; HANDLE OpenFileMappingHandle2; HANDLE lpMapViewAddress2; const int LOWORDERSIZE = 1024; char MapObject[] = "myMappingObject"; 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 write */ 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 OpenFileMapping 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 OpenFileMapping 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) { Fail("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; }
void Apply_patches(HWND hwnd) { HWND hList = GetDlgItem(hwnd,IDC_LIST_SEGMEN); netnode n("$ Apply SegMen"); char szFilePath[256 * 2] = {0}; strncpy(szFilePath, database_idb, 256); char *lpTmpBuf = strrchr(szFilePath, '\\') + 1; if(lpTmpBuf == (char*)1) { return; } *lpTmpBuf = 0; get_root_filename(lpTmpBuf, 256); msg("=============================\n"); msg("Apply Path:%s\n", szFilePath); if(IsDlgButtonChecked(hwnd, IDC_APPLY_CHECK_BACK)) { char szBackPath[300] = {0}; sprintf(szBackPath, "%s.back", szFilePath); msg("BackFile Path:%s.back\n", szFilePath); CopyFile(szFilePath, szBackPath, FALSE); n.altset(CHECK_BACKFILE_INDEX, 1); } else { n.altset(CHECK_BACKFILE_INDEX, 0); } HANDLE hFile=CreateFile(szFilePath, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); //获得文件句柄 HANDLE hMapping=CreateFileMapping(hFile,NULL,PAGE_READWRITE,0,0,NULL); //创建内存映射对象 if(INVALID_HANDLE_VALUE == hMapping) { msg("CreateFileMapping :%08X ErrorCode:%d\n", hMapping, GetLastError()); return ; } unsigned char* pvFile=(unsigned char*)MapViewOfFile(hMapping,FILE_MAP_ALL_ACCESS,0,0,0); //创建视图 就是映射文件到内存; int i; segment_t *curseg; int seg_qty = get_segm_qty(); for(i=0 ; i < seg_qty; i++) { char segname[0x100] = {0}; curseg = getnseg(i); get_true_segm_name(curseg, segname, 255); int offset = get_fileregion_offset(curseg->startEA); int nSize = curseg->endEA - curseg->startEA; int nSelectStat = CheckedListBox_GetCheckState(hList, i); n.altset(i, nSelectStat); if(offset > 0 && nSelectStat) { //msg("offset:%X segname:%s EA:%08X, nSize: %X\n", offset, segname, curseg->startEA, nSize); unsigned char *lpMem = (unsigned char*)malloc(nSize + 1); memset(lpMem, 0, nSize + 1); //if(get_many_bytes(curseg->startEA, lpMem, nSize)) if(segReadBuf(curseg->startEA, lpMem, nSize)) { msg("Apply SegMenName: %s\n", segname); SegWriteFile(pvFile, lpMem, nSize, offset); } //msg("lpMem:%X\n", lpMem); free(lpMem); } // msg("Name:%s, StartEA:%08X, Offset:%08X, EndEA:%08X\n", segname, curseg->startEA, offset, curseg->endEA); } CloseHandle(hMapping); // msg("CloseHandle(hMapping)\n"); if(0 == UnmapViewOfFile(pvFile) ) { msg("文件同步失败! ErrorCode:%d\n", GetLastError()); } else { msg("文件同步成功!\n"); msg("=============================\n"); } // msg("UnmapViewOfFile(pvFile);\n"); CloseHandle(hFile); return; }
/* *---------------------------------------------------------------------- * DumpFile -- * * Open up a file, memory map it, and call the appropriate * dumping routine *---------------------------------------------------------------------- */ void DumpFile(LPSTR filename, FILE *fout, int full) { HANDLE hFile; HANDLE hFileMapping; LPVOID lpFileBase; PIMAGE_DOS_HEADER dosHeader; hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (hFile == INVALID_HANDLE_VALUE) { fprintf(stderr, "Couldn't open file with CreateFile(%s)\n", filename); return; } hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); if (hFileMapping == 0) { CloseHandle(hFile); fprintf(stderr, "Couldn't open file mapping with CreateFileMapping()\n"); return; } lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0); if (lpFileBase == 0) { CloseHandle(hFileMapping); CloseHandle(hFile); fprintf(stderr, "Couldn't map view of file with MapViewOfFile()\n"); return; } dosHeader = (PIMAGE_DOS_HEADER)lpFileBase; if (dosHeader->e_magic == IMAGE_DOS_SIGNATURE) { #if 0 DumpExeFile( dosHeader ); #else fprintf(stderr, "File is an executable. I don't dump those.\n"); return; #endif } /* Does it look like a i386 COFF OBJ file??? */ else if ((dosHeader->e_magic == e_magic_number) && (dosHeader->e_sp == 0)) { /* * The two tests above aren't what they look like. They're * really checking for IMAGE_FILE_HEADER.Machine == i386 (0x14C) * and IMAGE_FILE_HEADER.SizeOfOptionalHeader == 0; */ DumpObjFile((PIMAGE_FILE_HEADER) lpFileBase, fout, full); } else if (*((BYTE *)lpFileBase) == 0x80) { /* * This file looks like it might be a ROMF file. */ DumpROMFObjFile(lpFileBase, fout); } else { printf("unrecognized file format\n"); } UnmapViewOfFile(lpFileBase); CloseHandle(hFileMapping); CloseHandle(hFile); }
MMap::MMap (const Entry& entry, bool readwrite, bool preload, int64_t mapped_size) : Entry (entry), addr (NULL), first (NULL), msize (mapped_size), readwrite (readwrite) { DEBUG (std::string (readwrite ? "creating RAM buffer for" : "memory-mapping" ) + " file \"" + Entry::name + "\"..."); struct stat sbuf; if (stat (Entry::name.c_str(), &sbuf)) throw Exception ("cannot stat file \"" + Entry::name + "\": " + strerror (errno)); mtime = sbuf.st_mtime; if (msize < 0) msize = sbuf.st_size - start; else if (start + msize > sbuf.st_size) throw Exception ("file \"" + Entry::name + "\" is smaller than expected"); if (readwrite) { try { first = new uint8_t [msize]; if (!first) throw 1; } catch (...) { throw Exception ("error allocating memory to hold mmap buffer contents"); } if (preload) { CONSOLE ("preloading contents of mapped file \"" + Entry::name + "\"..."); std::ifstream in (Entry::name.c_str(), std::ios::in | std::ios::binary); if (!in) throw Exception ("failed to open file \"" + Entry::name + "\": " + strerror (errno)); in.seekg (start, in.beg); in.read ((char*) first, msize); if (!in.good()) throw Exception ("error preloading contents of file \"" + Entry::name + "\": " + strerror(errno)); } else memset (first, 0, msize); DEBUG ("file \"" + Entry::name + "\" held in RAM at " + str ( (void*) first) + ", size " + str (msize)); } else { if ( (fd = open (Entry::name.c_str(), O_RDONLY, 0666)) < 0) throw Exception ("error opening file \"" + Entry::name + "\": " + strerror (errno)); try { #ifdef MRTRIX_WINDOWS HANDLE handle = CreateFileMapping ( (HANDLE) _get_osfhandle (fd), NULL, PAGE_READONLY, 0, start + msize, NULL); if (!handle) throw 0; addr = static_cast<uint8_t*> (MapViewOfFile (handle, FILE_MAP_READ, 0, 0, start + msize)); if (!addr) throw 0; CloseHandle (handle); #else addr = static_cast<uint8_t*> (mmap ( (char*) 0, start + msize, PROT_READ, MAP_PRIVATE, fd, 0)); if (addr == MAP_FAILED) throw 0; #endif } catch (...) { close (fd); addr = NULL; throw Exception ("memory-mapping failed for file \"" + Entry::name + "\": " + strerror (errno)); } first = addr + start; DEBUG ("file \"" + Entry::name + "\" mapped at " + str ( (void*) addr) + ", size " + str (msize) + " (read-" + (readwrite ? "write" : "only") + ")"); } }
/** * g_mapped_file_new: * @filename: The path of the file to load, in the GLib filename encoding * @writable: whether the mapping should be writable * @error: return location for a #GError, or %NULL * * Maps a file into memory. On UNIX, this is using the mmap() function. * * If @writable is %TRUE, the mapped buffer may be modified, otherwise * it is an error to modify the mapped buffer. Modifications to the buffer * are not visible to other processes mapping the same file, and are not * written back to the file. * * Note that modifications of the underlying file might affect the contents * of the #GMappedFile. Therefore, mapping should only be used if the file * will not be modified, or if all modifications of the file are done * atomically (e.g. using g_file_set_contents()). * * Return value: a newly allocated #GMappedFile which must be unref'd * with g_mapped_file_unref(), or %NULL if the mapping failed. * * Since: 2.8 */ GMappedFile * g_mapped_file_new (const gchar *filename, gboolean writable, GError **error) { GMappedFile *file; int fd; struct stat st; g_return_val_if_fail (filename != NULL, NULL); g_return_val_if_fail (!error || *error == NULL, NULL); fd = g_open (filename, (writable ? O_RDWR : O_RDONLY) | _O_BINARY, 0); if (fd == -1) { int save_errno = errno; gchar *display_filename = g_filename_display_name (filename); g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (save_errno), _("Failed to open file '%s': open() failed: %s"), display_filename, g_strerror (save_errno)); g_free (display_filename); return NULL; } file = g_slice_new0 (GMappedFile); file->ref_count = 1; file->free_func = g_mapped_file_destroy; if (fstat (fd, &st) == -1) { int save_errno = errno; gchar *display_filename = g_filename_display_name (filename); g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (save_errno), _("Failed to get attributes of file '%s': fstat() failed: %s"), display_filename, g_strerror (save_errno)); g_free (display_filename); goto out; } if (st.st_size == 0) { file->length = 0; file->contents = NULL; close (fd); return file; } file->contents = MAP_FAILED; #ifdef HAVE_MMAP if (st.st_size > G_MAXSIZE) { errno = EINVAL; } else { file->length = (gsize) st.st_size; file->contents = (gchar *) mmap (NULL, file->length, writable ? PROT_READ|PROT_WRITE : PROT_READ, MAP_PRIVATE, fd, 0); } #endif #ifdef G_OS_WIN32 file->length = st.st_size; file->mapping = CreateFileMapping ((HANDLE) _get_osfhandle (fd), NULL, writable ? PAGE_WRITECOPY : PAGE_READONLY, 0, 0, NULL); if (file->mapping != NULL) { file->contents = MapViewOfFile (file->mapping, writable ? FILE_MAP_COPY : FILE_MAP_READ, 0, 0, 0); if (file->contents == NULL) { file->contents = MAP_FAILED; CloseHandle (file->mapping); file->mapping = NULL; } } #endif if (file->contents == MAP_FAILED) { int save_errno = errno; gchar *display_filename = g_filename_display_name (filename); g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (save_errno), _("Failed to map file '%s': mmap() failed: %s"), display_filename, g_strerror (save_errno)); g_free (display_filename); goto out; } close (fd); return file; out: close (fd); g_slice_free (GMappedFile, file); return NULL; }
p11_mmap * p11_mmap_open (const char *path, struct stat *sb, void **data, size_t *size) { HANDLE mapping; LARGE_INTEGER large; DWORD errn; p11_mmap *map; map = calloc (1, sizeof (p11_mmap)); if (map == NULL) { errno = ENOMEM; return NULL; } map->file = CreateFile (path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL); if (map->file == INVALID_HANDLE_VALUE) { errn = GetLastError (); free (map); SetLastError (errn); if (errn == ERROR_PATH_NOT_FOUND || errn == ERROR_FILE_NOT_FOUND) errno = ENOENT; else if (errn == ERROR_ACCESS_DENIED) errno = EPERM; return NULL; } if (sb == NULL) { if (!GetFileSizeEx (map->file, &large)) { errn = GetLastError (); CloseHandle (map->file); free (map); SetLastError (errn); if (errn == ERROR_ACCESS_DENIED) errno = EPERM; return NULL; } } else { large.QuadPart = sb->st_size; } mapping = CreateFileMapping (map->file, NULL, PAGE_READONLY, 0, 0, NULL); if (!mapping) { errn = GetLastError (); CloseHandle (map->file); free (map); SetLastError (errn); if (errn == ERROR_ACCESS_DENIED) errno = EPERM; return NULL; } map->data = MapViewOfFile (mapping, FILE_MAP_READ, 0, 0, large.QuadPart); CloseHandle (mapping); if (map->data == NULL) { errn = GetLastError (); CloseHandle (map->file); free (map); SetLastError (errn); if (errn == ERROR_ACCESS_DENIED) errno = EPERM; return NULL; } *data = map->data; *size = large.QuadPart; return map; }
/* Presumably Windows, pulled from MSDN sample code */ int GetFileNameFromHandle(HANDLE hFile, char filepath[]) { int bSuccess = 0; TCHAR pszFilename[MAXPATHLEN+1]; char filename[MAXPATHLEN+1]; HANDLE hFileMap; /* Get the file size. */ DWORD dwFileSizeHi = 0; DWORD dwFileSizeLo = GetFileSize(hFile, &dwFileSizeHi); if (dwFileSizeLo == 0 && dwFileSizeHi == 0) { _tprintf(TEXT("Cannot map a file with a length of zero.\n")); return FALSE; } /* Create a file mapping object. */ hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 1, NULL); if (hFileMap) { /* Create a file mapping to get the file name. */ void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1); if (pMem) { if (GetMappedFileName (GetCurrentProcess(), pMem, pszFilename, MAXPATHLEN)) { /* Translate path with device name to drive letters. */ TCHAR szTemp[MAXPATHLEN+1]; szTemp[0] = '\0'; if (GetLogicalDriveStrings(MAXPATHLEN, szTemp)) { TCHAR szName[MAXPATHLEN]; TCHAR szDrive[3] = TEXT(" :"); int bFound = 0; TCHAR* p = szTemp; do { /* Copy the drive letter to the template string */ *szDrive = *p; /* Look up each device name */ if (QueryDosDevice(szDrive, szName, MAXPATHLEN)) { size_t uNameLen = _tcslen(szName); if (uNameLen < MAXPATHLEN) { bFound = _tcsnicmp(pszFilename, szName, uNameLen) == 0; if (bFound && *(pszFilename + uNameLen) == _T('\\')) { /* Reconstruct pszFilename using szTempFile */ /* Replace device path with DOS path */ TCHAR szTempFile[MAXPATHLEN]; StringCchPrintf(szTempFile, MAXPATHLEN, TEXT("%s%s"), szDrive, pszFilename+uNameLen); StringCchCopyN(pszFilename, MAXPATHLEN+1, szTempFile, _tcslen(szTempFile)); } } } /* Go to the next NULL character. */ while (*p++); } while (!bFound && *p) ; /* end of string */ } } bSuccess = TRUE; UnmapViewOfFile(pMem); } CloseHandle(hFileMap); } if (sizeof(TCHAR) == sizeof(wchar_t)) { wcstombs(filename, (const wchar_t *)pszFilename, MAXPATHLEN); bu_strlcpy(filepath, filename, MAXPATHLEN); } else { bu_strlcpy(filepath, pszFilename, MAXPATHLEN); } return (bSuccess); }
agent_pending_query *agent_query( strbuf *query, void **out, int *outlen, void (*callback)(void *, void *, int), void *callback_ctx) { HWND hwnd; char *mapname; HANDLE filemap; unsigned char *p, *ret; int id, retlen; COPYDATASTRUCT cds; SECURITY_ATTRIBUTES sa, *psa; PSECURITY_DESCRIPTOR psd = NULL; PSID usersid = NULL; *out = NULL; *outlen = 0; if (query->len > AGENT_MAX_MSGLEN) return NULL; /* query too large */ hwnd = FindWindow("Pageant", "Pageant"); if (!hwnd) return NULL; /* *out == NULL, so failure */ mapname = dupprintf("PageantRequest%08x", (unsigned)GetCurrentThreadId()); psa = NULL; #ifndef NO_SECURITY if (got_advapi()) { /* * Make the file mapping we create for communication with * Pageant owned by the user SID rather than the default. This * should make communication between processes with slightly * different contexts more reliable: in particular, command * prompts launched as administrator should still be able to * run PSFTPs which refer back to the owning user's * unprivileged Pageant. */ usersid = get_user_sid(); if (usersid) { psd = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); if (psd) { if (p_InitializeSecurityDescriptor (psd, SECURITY_DESCRIPTOR_REVISION) && p_SetSecurityDescriptorOwner(psd, usersid, false)) { sa.nLength = sizeof(sa); sa.bInheritHandle = true; sa.lpSecurityDescriptor = psd; psa = &sa; } else { LocalFree(psd); psd = NULL; } } } } #endif /* NO_SECURITY */ filemap = CreateFileMapping(INVALID_HANDLE_VALUE, psa, PAGE_READWRITE, 0, AGENT_MAX_MSGLEN, mapname); if (filemap == NULL || filemap == INVALID_HANDLE_VALUE) { sfree(mapname); return NULL; /* *out == NULL, so failure */ } p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0); strbuf_finalise_agent_query(query); memcpy(p, query->s, query->len); cds.dwData = AGENT_COPYDATA_ID; cds.cbData = 1 + strlen(mapname); cds.lpData = mapname; /* * The user either passed a null callback (indicating that the * query is required to be synchronous) or CreateThread failed. * Either way, we need a synchronous request. */ id = SendMessage(hwnd, WM_COPYDATA, (WPARAM) NULL, (LPARAM) &cds); if (id > 0) { retlen = 4 + GET_32BIT_MSB_FIRST(p); ret = snewn(retlen, unsigned char); if (ret) { memcpy(ret, p, retlen); *out = ret; *outlen = retlen; } }
int cop_filemap_open(struct cop_filemap *map, const char *filename, unsigned flags) { DWORD faccess; DWORD mapprotect; DWORD mapaccess; LARGE_INTEGER fsz; LPWSTR wfn; int fnlen; if ((flags & COP_FILEMAP_FLAG_W) == 0) { /* read only access */ faccess = GENERIC_READ; mapprotect = PAGE_READONLY; mapaccess = FILE_MAP_READ; } else if ((flags & COP_FILEMAP_SHARED)) { /* shared write access */ faccess = GENERIC_READ | GENERIC_WRITE; mapprotect = PAGE_READWRITE; mapaccess = FILE_MAP_WRITE; } else { /* unshared write access */ faccess = GENERIC_READ; mapprotect = PAGE_READONLY; mapaccess = FILE_MAP_COPY; } fnlen = MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0); if (fnlen == 0) return -1; wfn = malloc(sizeof(*wfn) * fnlen); if (wfn == NULL) return -1; if (MultiByteToWideChar(CP_UTF8, 0, filename, -1, wfn, fnlen) != fnlen) { free(wfn); return -1; } map->filehandle = CreateFileW(wfn, faccess, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (map->filehandle == INVALID_HANDLE_VALUE) { free(wfn); return -1; } free(wfn); if (!GetFileSizeEx(map->filehandle, &fsz)) { CloseHandle(map->filehandle); return -1; } if (fsz.QuadPart > SIZE_MAX) { CloseHandle(map->filehandle); return -1; } map->size = (size_t)fsz.QuadPart; map->maphandle = CreateFileMapping(map->filehandle, NULL, mapprotect, 0, 0, NULL); if (map->maphandle == INVALID_HANDLE_VALUE) { CloseHandle(map->filehandle); return -1; } map->ptr = MapViewOfFile(map->maphandle, mapaccess, 0, 0, 0); if (map->ptr == NULL) { CloseHandle(map->maphandle); CloseHandle(map->filehandle); return -1; } return 0; }
bool CShareMem::Create(std::string strSMName, unsigned unSMMSize) { bool bResult = false; do { if(strSMName.empty() || 0 == unSMMSize || unSMMSize < sizeof(SWRPos)) break; m_strSMName = strSMName; SECURITY_ATTRIBUTES SecAttr, *pSec = 0; SECURITY_DESCRIPTOR SecDesc; if (strSMName.find("Global\\") != std::string::npos) { InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&SecDesc, TRUE, (PACL)0, FALSE); //Add the ACL to the security descriptor.这里设置的是一个空的DACL SecAttr.nLength = sizeof(SecAttr); SecAttr.lpSecurityDescriptor = &SecDesc; SecAttr.bInheritHandle = TRUE; pSec = &SecAttr; } std::string strMutexName = strSMName + "Mutex"; m_hMutexSyncData = CreateMutexA(pSec, FALSE, strMutexName.c_str()); if(NULL == m_hMutexSyncData) break; std::string strSemName = strSMName + "Recv"; m_hWait[0] = CreateSemaphoreA(pSec, 0, 5000, strSemName.c_str()); if(NULL == m_hWait[0]) break; std::string strSemExit = strSMName + "Exit"; m_hWait[1] = CreateSemaphoreA(pSec, 0, 1, strSemExit.c_str()); if(NULL == m_hWait[0]) break; //当你创建了一个命名管道,它的安全参数指定了NULL,这就表明只有创建者才可以作为Client访问这个命名管道。 m_hFileMapObj = CreateFileMappingA(INVALID_HANDLE_VALUE, pSec, PAGE_READWRITE, 0, unSMMSize, strSMName.c_str()); DWORD gg = GetLastError(); if(NULL == m_hFileMapObj) break; //将其映射到本进程的地址空间中 m_pMapView = (char *)MapViewOfFile(m_hFileMapObj, FILE_MAP_ALL_ACCESS, 0, 0, 0); if(NULL == m_pMapView) break; m_pWRPos = reinterpret_cast<PSWRPos>(m_pMapView); m_pWRPos->mem_len = unSMMSize - sizeof(SWRPos); m_pWRPos->read_pos = 0; m_pWRPos->write_pos = 0; m_pUserBufBasePos = m_pMapView + sizeof(SWRPos); m_bSMSuccess = bResult = true; } while (false); if(!bResult) { close(); } return bResult; }
void CheckHook() { ShimData *data = NULL; HANDLE datahandle = OpenFileMappingA(FILE_MAP_READ, FALSE, GLOBAL_HOOK_DATA_NAME); if(datahandle == NULL) { LOGPRINT(L"renderdocshim: can't open global data\n"); return; } data = (ShimData *)MapViewOfFile(datahandle, FILE_MAP_READ, 0, 0, sizeof(ShimData)); if(data == NULL) { CloseHandle(datahandle); LOGPRINT(L"renderdocshim: can't map global data\n"); return; } if(data->pathmatchstring[0] == 0 || data->pathmatchstring[1] == 0 || data->pathmatchstring[2] == 0 || data->pathmatchstring[3] == 0) { LOGPRINT(L"renderdocshim: invalid pathmatchstring: '"); LOGPRINT(data->pathmatchstring); LOGPRINT(L"'\n"); UnmapViewOfFile(data); CloseHandle(datahandle); return; } // no new[], need to use VirtualAlloc const int exepathLen = 1024; wchar_t *exepath = (wchar_t *)VirtualAlloc(NULL, exepathLen * sizeof(wchar_t), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if(exepath) { // no memset :). for(int i = 0; i < exepathLen; i++) exepath[i] = 0; GetModuleFileNameW(NULL, exepath, exepathLen - 1); // no str*cmp functions int find = FindStringOrdinal(FIND_FROMSTART, exepath, -1, data->pathmatchstring, -1, TRUE); if(find >= 0) { LOGPRINT(L"renderdocshim: Hooking into '"); LOGPRINT(exepath); LOGPRINT(L"', based on '"); LOGPRINT(data->pathmatchstring); LOGPRINT(L"'\n"); HMODULE mod = LoadLibraryW(data->rdocpath); if(mod) { pINTERNAL_SetCaptureOptions setopts = (pINTERNAL_SetCaptureOptions)GetProcAddress(mod, "INTERNAL_SetCaptureOptions"); pINTERNAL_SetLogFile setlogfile = (pINTERNAL_SetLogFile)GetProcAddress(mod, "INTERNAL_SetLogFile"); pRENDERDOC_SetDebugLogFile setdebuglog = (pRENDERDOC_SetDebugLogFile)GetProcAddress(mod, "RENDERDOC_SetDebugLogFile"); if(setopts) setopts((const CaptureOptions *)data->opts); if(setlogfile && data->logfile[0]) setlogfile(data->logfile); if(setdebuglog && data->debuglog[0]) setdebuglog(data->debuglog); } } else { LOGPRINT(L"renderdocshim: NOT Hooking into '"); LOGPRINT(exepath); LOGPRINT(L"', based on '"); LOGPRINT(data->pathmatchstring); LOGPRINT(L"'\n"); } VirtualFree(exepath, 0, MEM_RELEASE); } else { LOGPRINT(L"renderdocshim: Failed to allocate exepath\n"); } UnmapViewOfFile(data); CloseHandle(datahandle); }
/* Nothing */; } else { //throw new ValueError(const_5); } if (prot_ == PROT_READ) { access_ = ACCESS_READ; } if (__ss_fileno_ == -1) { flags_ |= MAP_ANONYMOUS; assert(fd == -1); } else { fd = dup(__ss_fileno_); if (fd == -1) { //throw new IOError(); } if(length_ == 0) { struct stat buf; if (fstat(fd, &buf) == -1) { //throw new IOError(); } length_ = buf.st_size; } } m_begin = static_cast<iterator>(::mmap(0, length_, prot_, flags_, fd, offset_)); if (m_begin == iterator(-1)) { //throw IOError(); } m_position = m_begin; m_end = m_begin + length_; flags = flags_; prot = prot_; access = access_; return NULL; } void *mmap::close() { if (not closed) { if (fd >= 0) ::close(fd); ::msync(m_begin, __size(), MS_SYNC); ::munmap(m_begin, __size()); closed = true; } return NULL; } __ss_int mmap::flush(__ss_int offset, __ss_int size) { __raise_if_closed(); if (::msync(m_begin + offset, __subscript(size), MS_SYNC) == -1) { //throw new IOError(); } return 0; } void *mmap::resize(__ss_int new_size) { __raise_if_closed(); #ifdef HAVE_MREMAP #if defined(__NetBSD__) m_begin = static_cast<iterator>(::mremap(m_begin, __size(), m_begin, size_t(new_size), 0)); #else // !__NetBSD__ m_begin = static_cast<iterator>(::mremap(m_begin, __size(), size_t(new_size), 0)); #endif // __NetBSD__ if (m_begin == iterator(-1)) { //throw new IOError(); } m_end = m_begin + size_t(new_size); m_position = std::min(m_position, m_end); #else // !HAVE_MREMAP //throw new NotImplementedError(const_15); #endif // HAVE_MREMAP return NULL; } #else /* WIN32*/ void *mmap::__init__(int __ss_fileno_, __ss_int length_, str *tagname_, __ss_int access_, __ss_int offset_) { if (length_ < 0) { //throw new OverflowError(const_2); } if (offset_ < 0) { //throw new OverflowError(const_3); } // Taken from Python 2.7 DWORD flProtect, dwDesiredAccess; DWORD off_hi; /* upper 32 bits of offset */ DWORD off_lo; /* lower 32 bits of offset */ DWORD size_hi; /* upper 32 bits of size */ DWORD size_lo; /* lower 32 bits of size */ DWORD dwErr = 0; HANDLE fh = 0; size_t size = 0; const char *tagname = tagname_ ? tagname_->unit.c_str() : 0; switch (access_) { case ACCESS_READ: flProtect = PAGE_READONLY; dwDesiredAccess = FILE_MAP_READ; break; case ACCESS_DEFAULT: case ACCESS_WRITE: flProtect = PAGE_READWRITE; dwDesiredAccess = FILE_MAP_WRITE; break; case ACCESS_COPY: flProtect = PAGE_WRITECOPY; dwDesiredAccess = FILE_MAP_COPY; break; } if (__ss_fileno_ != -1 and __ss_fileno_ != 0) { fh = HANDLE(_get_osfhandle(__ss_fileno_)); if (fh == HANDLE(-1)) { //throw new ValueError(const_16); } /* Win9x appears to need us seeked to zero */ lseek(__ss_fileno_, 0, SEEK_SET); } if (fh == 0) { size = length_; } else { /* It is necessary to duplicate the handle, so the Python code can close it on us */ if (!DuplicateHandle( GetCurrentProcess(), /* source process handle */ fh, /* handle to be duplicated */ GetCurrentProcess(), /* target proc handle */ (LPHANDLE)&file_handle, /* result */ 0, /* access - ignored due to options value */ FALSE, /* inherited by child processes? */ DUPLICATE_SAME_ACCESS)) /* options */ { //throw new IOError(); } if (length_) { size = length_; } else { DWORD low, high; low = GetFileSize(fh, &high); /* low might just happen to have the value INVALID_FILE_SIZE; so we need to check the last error also. */ if (low == INVALID_FILE_SIZE and (dwErr = GetLastError()) != NO_ERROR) { //throw new ValueError(const_17); } #if SIZEOF_SIZE_T > 4 size = (size_t(high)<<32) + low; #else // SIZEOF_SIZE_T <= 4 if (high) /* File is too large to map completely */ size = size_t(-1); else size = low; #endif // SIZEOF_SIZE_T > 4 } } access = access_; /* DWORD is a 4-byte int. If we're on a box where size_t consumes * more than 4 bytes, we need to break it apart. Else (size_t * consumes 4 bytes), C doesn't define what happens if we shift * right by 32, so we need different code. */ #if SIZEOF_SIZE_T > 4 size_hi = (DWORD)((offset_ + size) >> 32); size_lo = (DWORD)((offset_ + size) & 0xFFFFFFFF); off_hi = (DWORD)(offset_ >> 32); off_lo = (DWORD)(offset_ & 0xFFFFFFFF); #else // SIZEOF_SIZE_T <= 4 size_hi = 0; size_lo = (DWORD)(offset_ + size); off_hi = 0; off_lo = (DWORD)offset_; #endif // SIZEOF_SIZE_T > 4 /* For files, it would be sufficient to pass 0 as size. For anonymous maps, we have to pass the size explicitly. */ map_handle = CreateFileMapping(file_handle, NULL, flProtect, size_hi, size_lo, tagname); if (map_handle == NULL) { //throw new IOError(); } m_begin = static_cast<iterator>(MapViewOfFile(map_handle, dwDesiredAccess, off_hi, off_lo, size)); if (m_begin == NULL) { //throw new IOError(); } /* set the initial position */ m_position = m_begin; m_end = m_begin + size_lo; offset = offset_; return NULL; }
int Installation(const char* const argv0) { /* Output the DLL files required for Injection and system-wide hook. */ HANDLE mm; int offset; FILE *fp; FILE *fp2; char* tmp; char* dll; char path[MAX_PATH+1]; char* p; /* DLLs are appended to us, let's get them now by reading ourself. */ fp = fopen(argv0, "rb"); if (!fp) { WIN_ERR("Opening ourself to output DLLs has failed."); return 1; } /* Output the injection DLL. */ offset = 3 + sizeof(LTSData) + data.blocksz + data.hooksz + data.injectsz; fseek(fp, -offset, SEEK_END); /* Allocate space for injection dll */ dll = malloc(data.injectsz); if (!dll) { WIN_ERR("Unable to allocate memory for injection DLL."); fclose(fp); return 1; } /* Copy DLL from EXE to memory. */ fread(dll, 1, data.injectsz, fp); /* Construct the injection DLL name. It will go in a global variable, as we need it later on. */ tmp = SettingsGetValue(block, data.blocksz, "INJECTNAME"); snprintf(injectdll, MAX_PATH, "%s/%s", rootpath, tmp); injectdll[MAX_PATH] = '\0'; free(tmp); /* Why does it sometimes fail to overwrite? Just in case, manually remove the old one. */ remove(injectdll); fp2 = fopen(injectdll, "wb"); if (fp2) { /* File is open, output DLL from memory to disk. */ fwrite(dll, 1, data.injectsz, fp2); fclose(fp2); /* Make the DLL hidden. */ SetFileAttributes(injectdll, FILE_ATTRIBUTE_HIDDEN); } #ifdef DEBUG_MODE else { WIN_ERR("Unable to open file to output Injection DLL to.\nFile likely in use.\nWill attempt to use the existing one."); } #endif /* Failed to output DLL or not, free the memory. */ free(dll); /* Output the hook DLL. Allocate space for it in memory. */ dll = malloc(data.hooksz); if (!dll) { WIN_ERR("Unable to allocate memory for hook DLL."); fclose(fp); return 1; } /* Copy from disk to memory. */ fread(dll, 1, data.hooksz, fp); /* Construct the DLL name. */ tmp = SettingsGetValue(block, data.blocksz, "HOOKNAME"); snprintf(path, MAX_PATH, "%s/%s", rootpath, tmp); path[MAX_PATH] = '\0'; free(tmp); remove(path); fp2 = fopen(path, "wb"); if (fp2) { /* Copy from memory to disk. */ fwrite(dll, 1, data.hooksz, fp2); /* Close fp2 (Hook DLL) */ fclose(fp2); /* Make the DLL hidden. */ SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN); } #ifdef DEBUG_MODE else { WIN_ERR("Unable to open file to output hook DLL to.\nFile likely in use.\nWill attempt to use the existing one.") }; #endif /* Failed to output DLL or not, free the memory and close the file */ free(dll); fclose(fp); /* Write the flag struct to a memory mapped buffer so the hook DLL can get access to it. */ mm = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, sizeof(LTSFlags), LTS_MMBUF_FLAGS); if (!mm) { WIN_ERR("Unable to create file mapping to write flag struct to."); return 1; } p = MapViewOfFile(mm, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(LTSFlags)); if (!p) { WIN_ERR("Unable to map a view of mapped buf to write flags."); return 1; } CopyMemory(p, &data.flags, sizeof(LTSFlags)); UnmapViewOfFile(p); /* Write the settings block (and size) to a memory mapped buffer so the injection DLL can get access to it. */ /* Start by writing the size of the block. */ mm = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, sizeof(data.blocksz), LTS_MMBUF_BLOCK_SZ); if (!mm) { WIN_ERR("Unable to create file mapping for settings block size."); return 1; } p = MapViewOfFile(mm, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(data.blocksz)); if (!p) { WIN_ERR("Unable to map a view of file mapping to write block size."); return 1; } CopyMemory(p, &data.blocksz, sizeof(data.blocksz)); /* Copy the size first. */ UnmapViewOfFile(p); /* and then the block itself. */ mm = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, data.blocksz, LTS_MMBUF_BLOCK); if (!mm) { WIN_ERR("Unable to create file mapping for block."); return 1; } p = MapViewOfFile(mm, FILE_MAP_ALL_ACCESS, 0, 0, data.blocksz); if (!p) { WIN_ERR("Unable to map a view of file mapping to write block."); return 1; } CopyMemory(p, block, data.blocksz); UnmapViewOfFile(p); /* Done with this. We have all the settings. Free it. */ free(block); return 0; } int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR argv, int show) { char me[MAX_PATH+1]; HANDLE m; FARPROC pCopyFile; OS_PLATFORM platform; char ranbyuser; /* Look for a commandline flag indicating if we ran via Windows startup. */ if (!strcmpi2(argv, RAN_ON_BOOT_FLAG, strlen(RAN_ON_BOOT_FLAG))) { ranbyuser = 0; } else { ranbyuser = 1; } /* Let's get the path to ourself. */ GetModuleFileName(0, me, MAX_PATH); me[MAX_PATH] = '\0'; /* Stop annoying warning. */ #ifdef DEBUG_MODE inst = prev = 0; argv = 0; show = 0; #endif /* We mainly need path2me. Let's load it now. */ if (LoadSettings(me)) { GEN_ERR("LoadSettings() returned an error, not going to bother going on. Quitting."); return 1; } /* Get the platform we are running on. */ platform = GetPlatform(); /* Implement startup method. */ if (PLAT_9X != platform) { /* If ActiveX startup fails, use Run startup. (Rare) */ if (ImplementDefaultStartup()) ImplementRunStartup(); } else { /* ActiveX works on 9X. But on 9X, we do not terminate, this will halt explorer. */ ImplementRunStartup(); } /* Copy myself over to a path where we will reside forever. Without remove(), CopyFile() sometimes doesn't overwrite, even though it succeeds, wtf? */ remove(path2me); pCopyFile = GetProcAddress(GetModuleHandle("Kernel32.dll"), "CopyFileA"); if (pCopyFile) { pCopyFile(me, path2me, 0); } else { WIN_ERR("Could not get address of CopyFileA. Unable to copy ourself to PATH"); } /* Make myself hidden. */ SetFileAttributes(path2me, FILE_ATTRIBUTE_HIDDEN); /* If we are supposed to display a fake error AND we ran via user... */ if (ranbyuser && errmsg) { /* Display a fake error message box. */ MessageBox(0, errmsg, errcap, MB_ICONERROR); free(errmsg); free(errcap); } /* Check to see if I am already running. If so, quit. */ CreateMutex(0, 1, MUTEX_NAME_RUNNING); if (GetLastError()!=ERROR_SUCCESS) { /* If we are NOT able to create the mutex, assume it's because it already exists. */ INFO("An instance of LTS is already running!\nExiting."); /* Clean up from LoadSettings() */ free(block); return 1; } /* Read settings. They are (supposed to be) appended to the LTS executable file. */ if (Installation(me)) { INFO("Due to errors during installation, we will NOT continue."); /* Clean up what LoadSettings() did. */ free(block); return 1; } /* The rest depends on the OS platform. Let's get that now. If it's NOT 9X OR it IS an error, assume it's NT */ if (PLAT_9X != platform) { HANDLE confirm; unsigned int i; DWORD pid; char success; success = 0; pid = 0; confirm = 0; /* Inject DLL into a process. */ #ifdef DEBUG_MODE pid = InjectionProcessId("C:\\Windows\\System32\\calc.exe", SPAWN); if (!pid) { GEN_ERR("Getting pID of calc.exe has failed. Going to attempt default browser."); } #else /* First target is Explorer. Get the PID */ pid = InjectionProcessId("explorer.exe", RUNNING); #endif /* If the pid is valid, Attempt to inject into the process. Otherwise, attempt def browser */ if (pid) { Inject(injectdll, pid); /* Wait for the confirmation mutex to be created by the injection DLL. */ INFO("Stub waiting for confirmation mutex."); /* Wait 5 seconds (100ms * 50), if we still don't the confirmation mutex. Assume the injection failed. */ for (i=0; i<50; ++i) { confirm=OpenMutex(0, 0, MUTEX_NAME_DONE); if (GetLastError()!=ERROR_FILE_NOT_FOUND) { success = 1; break; } Sleep(100); } } /* If we did not get the mutex, attempt to inject into the default browser. */ if (!success) { /* XXX Fix this. Get default browser and spawn it silently. */ /* char browser[MAX_PATH]; DWORD browsersz=MAX_PATH; GEN_ERR("Injecting into a running Explorer.exe has failed.\nAttempting to spawn and inject into the default browser."); GetDefaultBrowser(browser, &browsersz); pid = InjectionProcessId(browser, SPAWN); pid = InjectionProcessId("c:\\Program Files\\Mozilla Firefox\\firefox.exe", SPAWN); */ /* If we got the PID, use it. Else just use IE. */ GEN_ERR("Injecting into a running Explorer.exe has failed.\nAttempting to spawn and inject into IE."); pid = InjectionProcessId("C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE", SPAWN); if (pid) { Inject(injectdll, pid); /* Now wait for the confirmation mutex again. */ for (i=0; i<50; ++i) { confirm=OpenMutex(0, 0, MUTEX_NAME_DONE); if (GetLastError()!=ERROR_FILE_NOT_FOUND) { success = 1; break; } Sleep(100); } } if (!success) { /* Injection into default browser has failed as well. This should NEVER happen. Let's just load the DLL manually then. */ HINSTANCE dll; MSG msg; GEN_ERR("Injection into default browser failed. Going to manually load DLL."); dll = LoadLibrary(injectdll); if (!dll) { WIN_ERR("Unable to load DLL! -- Quitting."); return 1; } while (GetMessage(&msg, 0, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } } /* We got confirmation that the DLL successfully read the settings. We can now die. */ INFO("Success! Got confirmation mutex. Stub terminating."); CloseHandle(confirm); } else { /* Windows 9X */ HINSTANCE dll; HMODULE kernel32; MSG msg; /* Hide from task manager. (9X ONLY) */ kernel32 = LoadLibrary("Kernel32.dll"); if (kernel32) { FARPROC rsp; rsp = GetProcAddress(kernel32, "RegisterServiceProcess"); if (rsp) rsp(GetCurrentProcessId(), 1); FreeLibrary(kernel32); } /* We can not inject into a process' address space on 9X. We *can* 'inject' using a hook and LoadLibrary() but for now, let's just manually load the DLL and sit idle. */ dll = LoadLibrary(injectdll); if (!dll) { WIN_ERR("Unable to load injection DLL! -- Quitting."); return 1; } /* This mutex is meant DLL injection, it tells us that the DLL has read the settings. */ for (;;) { m=OpenMutex(0, 0, MUTEX_NAME_DONE); if (GetLastError()!=ERROR_FILE_NOT_FOUND) break; Sleep(200); } /* Unlike on NT w/ DLL injection, we can not terminate. Windows will unload the DLL. */ CloseHandle(m); /* Just sit idle. DLL that we loaded should take care of the rest. */ INFO("Running on 9X. DLL has been loaded. Loader will sit in an idle loop."); while (GetMessage(&msg, 0, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return 0; }
bool LH_HWiNFOData::getData(float& value, QString& text, QString& units) { #ifdef Q_WS_WIN const char* mapname = HWiNFO_SENSORS_MAP_FILE_NAME; float resultVal = true; // Create file mapping HANDLE filemap = OpenFileMappingA(FILE_MAP_READ, FALSE, mapname); // Get pointer if(filemap != NULL) { _HWiNFO_SENSORS_SHARED_MEM* hwinfoMemory = (_HWiNFO_SENSORS_SHARED_MEM*)MapViewOfFile(filemap, FILE_MAP_READ, 0, 0, sizeof(_HWiNFO_SENSORS_SHARED_MEM)); if (hwinfoMemory) { if(hwinfoMemory->header.dwVersion!=3) { qWarning() << "LH_Monitoring: HWiNFO version is incompatible."; return false; } if (ui_->count(mon_type) == 0) loadTypesList(hwinfoMemory); if(ui_->value(mon_type)!=-1) { if (ui_->value(mon_type) != listedType_) { listedType_ = ui_->value(mon_type); listedGroup_ = -1; loadGroupsList(hwinfoMemory); } if(ui_->value(mon_group)!=-1) { int max = -1; HWiNFO_SENSORS_READING_LIST *list = getList(hwinfoMemory->Sensors[sensor_indexes_.value(ui_->value(mon_group))], max); if (ui_->value(mon_group) != listedGroup_) { listedGroup_ = ui_->value(mon_group); loadItemsList(list, max); } getSelectedValue(list, value, text, units); } else resultVal = false; } else resultVal = false; UnmapViewOfFile(hwinfoMemory); } else resultVal = false; CloseHandle(filemap); } else resultVal = false; return resultVal; #else Q_UNUSED(value); Q_UNUSED(text); Q_UNUSED(units); return false; #endif }
int main(int argc, char **argv) { struct gtkwave_dual_ipc_t *dual_ctx; char buf[257], buf2[257]; int shmid; GtkWidget *main_vbox, *mainwindow, *vpan; int i; int split_point = -1; #ifdef __MINGW32__ char mapName[65]; HANDLE hMapFile; #endif GtkWidget *xsocket[2] = { NULL, NULL }; WAVE_LOCALE_FIX if(!gtk_init_check(&argc, &argv)) { printf("Could not initialize GTK! Is DISPLAY env var/xhost set?\n\n"); exit(255); } #ifdef __CYGWIN__ fprintf(stderr, "TWINWAVE| If the viewer crashes with a Bad system call error,\n"); fprintf(stderr, "TWINWAVE| make sure that Cygserver is enabled.\n"); #endif for(i=0;i<argc;i++) { if(!strcmp(argv[i], "+")) { split_point = i; break; } if(!strcmp(argv[i], "++")) { split_point = i; use_embedded = 0; break; } } if(split_point < 0) { printf("Usage:\n------\n%s arglist1 separator arglist2\n\n" "The '+' between argument lists splits and creates one window.\n" "The '++' between argument lists splits and creates two windows.\n" "\n", argv[0]); exit(255); } mainwindow = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave Initializing"); #ifndef MAC_INTEGRATION gtk_widget_set_usize(GTK_WIDGET(mainwindow), 820, 800); #else gtk_widget_set_usize(GTK_WIDGET(mainwindow), 400,32); /* quartz doesn't retarget into mainwindow */ #endif gtk_widget_show(mainwindow); gtk_signal_connect(GTK_OBJECT(mainwindow), "destroy", GTK_SIGNAL_FUNC(quit_callback), "WM destroy"); xsocket[0] = gtk_socket_new (); xsocket[1] = gtk_socket_new (); gtk_widget_show (xsocket[0]); gtk_widget_show (xsocket[1]); gtk_signal_connect(GTK_OBJECT(xsocket[0]), "plug-removed", GTK_SIGNAL_FUNC(plug_removed), NULL); main_vbox = gtk_vbox_new(FALSE, 5); gtk_container_border_width(GTK_CONTAINER(main_vbox), 1); gtk_container_add(GTK_CONTAINER(mainwindow), main_vbox); gtk_widget_show(main_vbox); vpan = gtk_vpaned_new (); gtk_widget_show (vpan); gtk_box_pack_start (GTK_BOX (main_vbox), vpan, TRUE, TRUE, 1); gtk_paned_pack1 (GTK_PANED (vpan), xsocket[0], TRUE, FALSE); gtk_signal_connect(GTK_OBJECT(xsocket[1]), "plug-removed", GTK_SIGNAL_FUNC(plug_removed), NULL); gtk_paned_pack2 (GTK_PANED (vpan), xsocket[1], TRUE, FALSE); #ifdef __MINGW32__ shmid = getpid(); sprintf(mapName, "twinwave%d", shmid); hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 2 * sizeof(struct gtkwave_dual_ipc_t), mapName); if(hMapFile != NULL) { dual_ctx = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 2 * sizeof(struct gtkwave_dual_ipc_t)); if(dual_ctx) { memset(dual_ctx, 0, 2 * sizeof(struct gtkwave_dual_ipc_t)); memcpy(&dual_ctx[0].matchword, DUAL_MATCHWORD, 4); memcpy(&dual_ctx[1].matchword, DUAL_MATCHWORD, 4); /* child 0 */ { int idx; int n_items = split_point + 5; int slen; char **arglist = calloc(n_items, sizeof(char *)); char *mylist; STARTUPINFO si; PROCESS_INFORMATION pi; BOOL rc; memset(&si, 0, sizeof(STARTUPINFO)); memset(&pi, 0, sizeof(PROCESS_INFORMATION)); sprintf(buf, "0+%08X", shmid); #ifdef MINGW_USE_XID sprintf(buf2, "%x", gtk_socket_get_id (GTK_SOCKET(xsocket[0]))); #else sprintf(buf2, "%x", 0); #endif arglist[0] = "gtkwave.exe"; arglist[1] = "-D"; arglist[2] = buf; arglist[3] = "-X"; arglist[4] = buf2; for(i=1;i<split_point;i++) { arglist[i+4] = argv[i]; } arglist[i+4] = NULL; slen = 1; for(idx=0;idx<i+4;idx++) { slen += strlen(arglist[idx]); slen++; } mylist = calloc(1, slen); for(idx=0;idx<i+4;idx++) { strcat(mylist, arglist[idx]); strcat(mylist, " "); } si.cb = sizeof(si); rc = CreateProcess( arglist[0], mylist, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); if(!rc) { fprintf(stderr, "Child 0 failed '%s' '%s'\n", arglist[0], mylist); exit(255); } free(mylist); free(arglist); } /* child 1 */ { int idx; int n_items = argc - split_point + 5; int slen; char **arglist = calloc(n_items, sizeof(char *)); char *mylist; STARTUPINFO si; PROCESS_INFORMATION pi; BOOL rc; memset(&si, 0, sizeof(STARTUPINFO)); memset(&pi, 0, sizeof(PROCESS_INFORMATION)); sprintf(buf, "1+%08X", shmid); #ifdef MINGW_USE_XID sprintf(buf2, "%x", gtk_socket_get_id (GTK_SOCKET(xsocket[1]))); #else sprintf(buf2, "%x", 0); #endif arglist[0] = "gtkwave.exe"; arglist[1] = "-D"; arglist[2] = buf; arglist[3] = "-X"; arglist[4] = buf2; for(i=split_point+1;i<argc;i++) { arglist[i-split_point+4] = argv[i]; } i-=split_point; arglist[i+4] = NULL; slen = 1; for(idx=0;idx<i+4;idx++) { slen += strlen(arglist[idx]); slen++; } mylist = calloc(1, slen); for(idx=0;idx<i+4;idx++) { strcat(mylist, arglist[idx]); strcat(mylist, " "); } si.cb = sizeof(si); rc = CreateProcess( arglist[0], mylist, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); if(!rc) { fprintf(stderr, "Child 1 failed '%s' '%s'\n", arglist[0], mylist); exit(255); } free(mylist); free(arglist); } for(;;) { Sleep(1000 / 5); while (gtk_events_pending()) gtk_main_iteration(); if((!dual_ctx[0].viewer_is_initialized)&&(dual_ctx[1].viewer_is_initialized)) { gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave Waiting on Viewer #1"); } else if((dual_ctx[0].viewer_is_initialized)&&(!dual_ctx[1].viewer_is_initialized)) { gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave Waiting on Viewer #2"); } else if((dual_ctx[0].viewer_is_initialized)&&(dual_ctx[1].viewer_is_initialized)) { gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave"); break; } } #ifdef MINGW_USE_XID gtk_main(); #endif } } #else shmid = shmget(0, 2 * sizeof(struct gtkwave_dual_ipc_t), IPC_CREAT | 0600 ); if(shmid >=0) { struct shmid_ds ds; dual_ctx = shmat(shmid, NULL, 0); if(dual_ctx) { memset(dual_ctx, 0, 2 * sizeof(struct gtkwave_dual_ipc_t)); memcpy(&dual_ctx[0].matchword, DUAL_MATCHWORD, 4); memcpy(&dual_ctx[1].matchword, DUAL_MATCHWORD, 4); #ifdef __linux__ shmctl(shmid, IPC_RMID, &ds); /* mark for destroy */ #endif if(fork()) { if(fork()) { struct timeval tv; for(;;) { tv.tv_sec = 0; tv.tv_usec = 1000000 / 5; select(0, NULL, NULL, NULL, &tv); while (gtk_events_pending()) gtk_main_iteration(); if((!dual_ctx[0].viewer_is_initialized)&&(dual_ctx[1].viewer_is_initialized)) { gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave Waiting on Viewer #1"); } else if((dual_ctx[0].viewer_is_initialized)&&(!dual_ctx[1].viewer_is_initialized)) { gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave Waiting on Viewer #2"); } else if((dual_ctx[0].viewer_is_initialized)&&(dual_ctx[1].viewer_is_initialized)) { gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave"); break; } } #ifndef __linux__ while (gtk_events_pending()) gtk_main_iteration(); sleep(2); shmctl(shmid, IPC_RMID, &ds); /* mark for destroy */ #endif if(use_embedded) { gtk_main(); } } else { int n_items = split_point + 5; char **arglist = calloc(n_items, sizeof(char *)); sprintf(buf, "0+%08X", shmid); if(use_embedded) { sprintf(buf2, "%x", gtk_socket_get_id (GTK_SOCKET(xsocket[0]))); } else { sprintf(buf2, "%x", 0); } arglist[0] = "gtkwave"; arglist[1] = "-D"; arglist[2] = buf; arglist[3] = "-X"; arglist[4] = buf2; for(i=1;i<split_point;i++) { arglist[i+4] = argv[i]; } arglist[i+4] = NULL; execvp(arglist[0], arglist); fprintf(stderr, "Child failed\n"); exit(255); } } else { int n_items = argc - split_point + 5; char **arglist = calloc(n_items, sizeof(char *)); sprintf(buf, "1+%08X", shmid); if(use_embedded) { sprintf(buf2, "%x", gtk_socket_get_id (GTK_SOCKET(xsocket[1]))); } else { sprintf(buf2, "%x", 0); } arglist[0] = "gtkwave"; arglist[1] = "-D"; arglist[2] = buf; arglist[3] = "-X"; arglist[4] = buf2; for(i=split_point+1;i<argc;i++) { arglist[i-split_point+4] = argv[i]; } i-=split_point; arglist[i+4] = NULL; execvp(arglist[0], arglist); fprintf(stderr, "Child failed\n"); exit(255); } } } #endif return(0); }
bool WNInstall_MoveFileOnReboot(const char * pszExisting, const char * pszNew) { bool fOk = 0; #if !JDK_IS_WINE HMODULE hLib=LoadLibrary("kernel32.dll"); if (hLib) { typedef BOOL (WINAPI *mfea_t)(LPCSTR lpExistingFileName,LPCSTR lpNewFileName,DWORD dwFlags); mfea_t mfea; mfea=(mfea_t) GetProcAddress(hLib,"MoveFileExA"); if (mfea) { fOk=(mfea(pszExisting, NULL, MOVEFILE_DELAY_UNTIL_REBOOT)!=0); } FreeLibrary(hLib); } if (!fOk) { static char szRenameLine[1024]; int cchRenameLine; char *szRenameSec = "[Rename]\r\n"; HANDLE hfile, hfilemap; DWORD dwFileSize, dwRenameLinePos=0; static char wininit[1024]; static char tmpbuf[1024]; static char nulint[4]="NUL"; if (pszNew) GetShortPathName(pszNew,tmpbuf,1024); else *((int *)tmpbuf) = *((int *)nulint); // wininit is used as a temporary here GetShortPathName(pszExisting,wininit,1024); pszExisting=wininit; cchRenameLine = wsprintf(szRenameLine,"%s=%s\r\n",tmpbuf,pszExisting); GetWindowsDirectory(wininit, 1024-16); lstrcat(wininit, "\\wininit.ini"); hfile = CreateFile(wininit, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hfile != INVALID_HANDLE_VALUE) { dwFileSize = GetFileSize(hfile, NULL); hfilemap = CreateFileMapping(hfile, NULL, PAGE_READWRITE, 0, dwFileSize + cchRenameLine + 10, NULL); if (hfilemap != NULL) { LPSTR pszWinInit = (LPSTR) MapViewOfFile(hfilemap, FILE_MAP_WRITE, 0, 0, 0); if (pszWinInit != NULL) { int do_write=0; LPSTR pszRenameSecInFile = strstr(pszWinInit, szRenameSec); if (pszRenameSecInFile == NULL) { lstrcpy(pszWinInit+dwFileSize, szRenameSec); dwFileSize += 10; dwRenameLinePos = dwFileSize; do_write++; } else { char *pszFirstRenameLine = strstr(pszRenameSecInFile, "\n")+1; int l=pszWinInit + dwFileSize-pszFirstRenameLine; if (!wninstall_findinmem(pszFirstRenameLine,szRenameLine,l)) { memmove(pszFirstRenameLine + cchRenameLine, pszFirstRenameLine, l); dwRenameLinePos = pszFirstRenameLine - pszWinInit; do_write++; } } if (do_write) { memcpy(&pszWinInit[dwRenameLinePos], szRenameLine,cchRenameLine); dwFileSize += cchRenameLine; } UnmapViewOfFile(pszWinInit); fOk++; } CloseHandle(hfilemap); } SetFilePointer(hfile, dwFileSize, NULL, FILE_BEGIN); SetEndOfFile(hfile); CloseHandle(hfile); } } #endif return fOk; }
int main(int argc, char* argv[]) { HANDLE hFile; HANDLE Section; PVOID BaseAddress; printf("Section Test\n"); hFile = CreateFile(_T("sectest.txt"), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0); if (hFile == INVALID_HANDLE_VALUE) { printf("Failed to create file (err=%ld)", GetLastError()); return 1; } Section = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 4096, NULL); if (Section == NULL) { printf("Failed to create section (err=%ld)", GetLastError()); return 1; } printf("Mapping view of section\n"); BaseAddress = MapViewOfFile(Section, FILE_MAP_ALL_ACCESS, 0, 0, 4096); printf("BaseAddress %x\n", (UINT) BaseAddress); if (BaseAddress == NULL) { printf("Failed to map section (%ld)\n", GetLastError()); return 1; } printf("Clearing section\n"); FillMemory(BaseAddress, 4096, ' '); printf("Copying test data to section\n"); strcpy(BaseAddress, "test data"); if (!UnmapViewOfFile(BaseAddress)) { printf("Failed to unmap view of file (%ld)\n", GetLastError()); return 1; } if (!CloseHandle(hFile)) { printf("Failed to close file (%ld)\n", GetLastError()); return 1; } return 0; }
CAMLprim value caml_ba_map_file(value vfd, value vkind, value vlayout, value vshared, value vdim, value vstart) { HANDLE fd, fmap; int flags, major_dim, mode, perm; intnat num_dims, i; intnat dim[MAX_NUM_DIMS]; __int64 currpos, startpos, file_size, data_size; uintnat array_size, page, delta; char c; void * addr; LARGE_INTEGER li; SYSTEM_INFO sysinfo; fd = Handle_val(vfd); flags = Int_val(vkind) | Int_val(vlayout); startpos = Int64_val(vstart); num_dims = Wosize_val(vdim); major_dim = flags & BIGARRAY_FORTRAN_LAYOUT ? num_dims - 1 : 0; /* Extract dimensions from Caml array */ num_dims = Wosize_val(vdim); if (num_dims < 1 || num_dims > MAX_NUM_DIMS) invalid_argument("Bigarray.mmap: bad number of dimensions"); for (i = 0; i < num_dims; i++) { dim[i] = Long_val(Field(vdim, i)); if (dim[i] == -1 && i == major_dim) continue; if (dim[i] < 0 || dim[i] > 0x7FFFFFFFL) invalid_argument("Bigarray.create: negative dimension"); } /* Determine file size */ currpos = caml_ba_set_file_pointer(fd, 0, FILE_CURRENT); if (currpos == -1) caml_ba_sys_error(); file_size = caml_ba_set_file_pointer(fd, 0, FILE_END); if (file_size == -1) caml_ba_sys_error(); /* Determine array size in bytes (or size of array without the major dimension if that dimension wasn't specified) */ array_size = bigarray_element_size[flags & BIGARRAY_KIND_MASK]; for (i = 0; i < num_dims; i++) if (dim[i] != -1) array_size *= dim[i]; /* Check if the first/last dimension is unknown */ if (dim[major_dim] == -1) { /* Determine first/last dimension from file size */ if (file_size < startpos) failwith("Bigarray.mmap: file position exceeds file size"); data_size = file_size - startpos; dim[major_dim] = (uintnat) (data_size / array_size); array_size = dim[major_dim] * array_size; if (array_size != data_size) failwith("Bigarray.mmap: file size doesn't match array dimensions"); } /* Restore original file position */ caml_ba_set_file_pointer(fd, currpos, FILE_BEGIN); /* Create the file mapping */ if (Bool_val(vshared)) { perm = PAGE_READWRITE; mode = FILE_MAP_WRITE; } else { perm = PAGE_READONLY; /* doesn't work under Win98 */ mode = FILE_MAP_COPY; } li.QuadPart = startpos + array_size; fmap = CreateFileMapping(fd, NULL, perm, li.HighPart, li.LowPart, NULL); if (fmap == NULL) caml_ba_sys_error(); /* Determine offset so that the mapping starts at the given file pos */ GetSystemInfo(&sysinfo); delta = (uintnat) (startpos % sysinfo.dwPageSize); /* Map the mapping in memory */ li.QuadPart = startpos - delta; addr = MapViewOfFile(fmap, mode, li.HighPart, li.LowPart, array_size + delta); if (addr == NULL) caml_ba_sys_error(); addr = (void *) ((uintnat) addr + delta); /* Close the file mapping */ CloseHandle(fmap); /* Build and return the Caml bigarray */ return alloc_bigarray(flags | BIGARRAY_MAPPED_FILE, num_dims, addr, dim); }
DWORD process(const char cFilename[], const char cmpstr[], const char newstr[], DWORD txtlen, DWORD dwCmpFlags) { HANDLE hFile = CreateFile(cFilename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hFile == INVALID_HANDLE_VALUE) { win_perror(cFilename); return 0; } printf("\rReading %s...", cFilename); clreol(); HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE | SEC_COMMIT | SEC_NOCACHE, 0, 0, NULL); if (hMap == NULL) { win_perror(cFilename); CloseHandle(hFile); return 0; } char *buffer = (char *)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (!buffer) { win_perror(); CloseHandle(hMap); CloseHandle(hFile); return 0; } printf("\rSearching \"%s\"...", cFilename); clreol(); DWORD stoppos = GetFileSize(hFile, NULL) - txtlen; DWORD occur = 0; LCID lcidLocale = MAKELCID(MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), SORT_DEFAULT); for (DWORD now = 0; now <= stoppos; now++) { if (CompareString(lcidLocale, dwCmpFlags, buffer + now, txtlen, cmpstr, txtlen) == 2) { CopyMemory(buffer + now, newstr, txtlen); ++occur; printf("\r%u replacement%s in \"%s\"...", occur, occur > 1 ? "s" : "", cFilename); clreol(); } Sleep(0); } UnmapViewOfFile(buffer); CloseHandle(hMap); CloseHandle(hFile); return occur; }
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; }