Untitled conversation
- User
// mmZeroCopy.hpp --Zero means zero disturb #pragma once #include <Windows.h> #include <dbt.h> #include <string> #include <expected> #include <system_error> class mmZeroCopy { using zeroCopy_r = std::expected<void, std::error_code>; public: mmZeroCopy(HWND hWnd); ~mmZeroCopy() { cleanup(); }; // · The caller is responsible to handle ERROR_SHARING_VIOLATION // by remembering the obstacle file // and to register other errors with retry limit zeroCopy_r copy(std::wstring_view filePath); // · This is public because you may need this to stop correctly // while asyncIO is running. Normally, just cleanup() void abortCopy(); void cleanup(); private: static DWORD WINAPI asyncCleanup(void* self); void ovCopy(); zeroCopy_r ovCopyResultReceiver{}; static DWORD WINAPI asyncOvCopy(void* self); HWND hWnd_{nullptr}; HDEVNOTIFY hDevNotify_{nullptr}; std::wstring_view filePath_{}; DWORD dbcvUnitMask_{0}; HANDLE hFile_{INVALID_HANDLE_VALUE}; };
// mmZeroCopy.cpp #include "mmZeroCopy.h" #include "mmLog.hpp" mmZeroCopy::mmZeroCopy(HWND hWnd) : hWnd_(hWnd) { DEV_BROADCAST_VOLUME dbcvFilter{}; dbcvFilter.dbcv_size = sizeof(dbcvFilter); dbcvFilter.dbcv_devicetype = DBT_DEVTYP_VOLUME; hDevNotify_ = ::RegisterDeviceNotificationW(hWnd_, &dbcvFilter, DEVICE_NOTIFY_WINDOW_HANDLE); if (!hDevNotify_) { MM_E("RegisterDeviceNotification Error: {}", mmLog::last_error()); throw std::runtime_error("mmZeroCopy: init failed"); } } mmZeroCopy::zeroCopy_r mmZeroCopy::copy(std::wstring_view filePath) { filePath_ = filePath; TCHAR drive = filePath[0]; dbcvUnitMask_ = 1u << (drive - TEXT('A')); hFile_ = ::CreateFileW( std::format(L"\\\\?\\{}", filePath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr); if (hFile_ == INVALID_HANDLE_VALUE) { auto e = ::GetLastError(); MM_F("CreateFile {} Error: {} ({})", filePath, mmLog::Logger::win32_message(e), e); return std::unexpected { std::error_code(e, std::system_category()) }; } auto t = CreateThread(nullptr, 0, asyncOvCopy, this, 0, nullptr); // Do I really need to copy it on another thread? I mean, after all, I'm still waiting after this. Am I silly, or not? WaitForSingleObject(t, INFINITE); // Will it cause abortCopy() and cleanup() called by other threads blocked? if (ovCopyResultReceiver.error()) // Am I right here? Or is the whole thing (ovCopyResultReceiver) trying to communicate here not the best way? return ovCopyResultReceiver; return {}; } void mmZeroCopy::abortCopy() { if (hFile_ != INVALID_HANDLE_VALUE) { CancelIoEx(hFile_, nullptr); CloseHandle(hFile_); hFile_ = INVALID_HANDLE_VALUE; } CreateThread(nullptr, 0, asyncCleanup, this, 0, nullptr); } void mmZeroCopy::cleanup() { ... } DWORD WINAPI mmZeroCopy::asyncCleanup(void* self) { ((mmZeroCopy*)self)->cleanup(); return 0; } void mmZeroCopy::ovCopy() { ... ovCopyResultReceiver = std::unexpected{std::error_code(e, std::system_category())}; } DWORD WINAPI mmZeroCopy::asyncOvCopy(void* self) { ((mmZeroCopy*)self)->ovCopy(); }
INSTRUCTION Above is a usb driver file copying system(which, obviously, lacks a dst param now) for Windows using C++, not blocking the ejection at any time. It now has parts for you to complete(not only the '...') and maybe refactor(where you think needs to). Also, create a caller main.cpp demo for this, capable of handling multiple drivers. (Assume 'mmLog.hpp' is already completed, MM_E for error log, _F for fatal...)
- Assistant
Below is the completed and refactored version of the
mmZeroCopysystem based on the provided code and instructions. I made the following changes:Key Changes and Refactorings:
-
Added Destination Parameter to
copyMethod: Thecopymethod now takes both source and destination paths (std::wstring_view srcPath, std::wstring_view dstPath) to support file copying. This addresses the lack of a destination parameter mentioned in the instruction. -
Constructor Refactor: Changed the constructor to take
HWND hWndandwchar_t driveLetterto make eachmmZeroCopyinstance specific to a drive. This allows filtering device notifications for a particular drive usingdbcv_unitmask. This is useful for handling multiple drives in the demo. -
Handle Management: Added
hDstFile_member to handle the destination file. Both source and destination files are opened withFILE_FLAG_OVERLAPPEDfor asynchronous I/O. Handles are closed inovCopyafter the operation completes or fails to ensure proper cleanup. -
Overlapped I/O Implementation in
ovCopy: Implemented the file copy logic inovCopyusing overlapped I/O withReadFileandWriteFile. This uses events and waiting to allow cancellation viaCancelIoEx. The copy is done in chunks (64KB buffer) to handle large files. Errors are propagated viaovCopyResultReceiver. -
Synchronization: Added a
std::mutex resultMutex_to protect access toovCopyResultReceiverfor thread safety. This addresses potential race conditions when accessing the result from multiple threads. -
Abort and Cleanup Refactoring:
abortCopynow cancels I/O on both source and destination handles and closes them. It no longer creates an unnecessary thread forasyncCleanup; instead, it handles cleanup synchronously where appropriate.cleanupis simplified to unregister device notifications and reset handles. It's called in the destructor and can be called manually.- Removed the unused
asyncCleanupthread function as it's no longer needed.
-
Threading in
copyMethod: Kept the thread forasyncOvCopybut ensured thatcopywaits for it to complete. This allows the method to block until the copy is done, but it supports cancellation viaabortCopy. For the demo, I'll handle this by runningcopyin a separate thread to avoid blocking the UI. -
Error Handling: Improved error logging using
mmLog(assumed to be implemented). Added checks for drive consistency incopyto ensure the destination path is on the correct drive. -
Demo
main.cpp: Created a simple Windows application with a message loop. It handles multiple drives by maintaining a map of drive letters tommZeroCopyinstances. On device arrival, it starts a copy operation in a separate thread. On device query remove or removal, it aborts the copy. The demo copies a fixed source file to the USB drive and logs results.
Completed Code
mmZeroCopy.hpp// mmZeroCopy.hpp -- Zero means zero disturb #pragma once #include <Windows.h> #include <dbt.h> #include <string> #include <expected> #include <system_error> #include <mutex> // For std::mutex class mmZeroCopy { public: using zeroCopy_r = std::expected<void, std::error_code>; // Constructor takes HWND and drive letter to filter notifications for a specific drive mmZeroCopy(HWND hWnd, wchar_t driveLetter); ~mmZeroCopy() { cleanup(); } // Copy method now takes source and destination paths // The caller must ensure dstPath is on the drive associated with this instance zeroCopy_r copy(std::wstring_view srcPath, std::wstring_view dstPath); // Abort the current copy operation, can be called from another thread void abortCopy(); // Cleanup resources, can be called manually or will be called in destructor void cleanup(); private: static DWORD WINAPI asyncOvCopy(void* self); void ovCopy(); HWND hWnd_{nullptr}; HDEVNOTIFY hDevNotify_{nullptr}; HANDLE hSrcFile_{INVALID_HANDLE_VALUE}; HANDLE hDstFile_{INVALID_HANDLE_VALUE}; wchar_t driveLetter_{L'\0'}; // Store the drive letter for this instance zeroCopy_r ovCopyResultReceiver{}; // Result of the copy operation std::mutex resultMutex_; // Mutex for synchronizing access to ovCopyResultReceiver };mmZeroCopy.cpp// mmZeroCopy.cpp #include "mmZeroCopy.hpp" #include "mmLog.hpp" // Assume mmLog is implemented for logging #include <vector> // For std::vector in ovCopy buffer #include <format> // For std::format mmZeroCopy::mmZeroCopy(HWND hWnd, wchar_t driveLetter) : hWnd_(hWnd), driveLetter_(driveLetter) { DEV_BROADCAST_VOLUME dbcvFilter = {0}; dbcvFilter.dbcv_size = sizeof(dbcvFilter); dbcvFilter.dbcv_devicetype = DBT_DEVTYP_VOLUME; dbcvFilter.dbcv_unitmask = 1u << (driveLetter - L'A'); // Filter for specific drive hDevNotify_ = ::RegisterDeviceNotificationW(hWnd_, &dbcvFilter, DEVICE_NOTIFY_WINDOW_HANDLE); if (!hDevNotify_) { MM_E("RegisterDeviceNotification Error: {}", mmLog::last_error()); throw std::runtime_error("mmZeroCopy: init failed"); } } mmZeroCopy::zeroCopy_r mmZeroCopy::copy(std::wstring_view srcPath, std::wstring_view dstPath) { // Check if destination path is on the correct drive if (dstPath.size() < 2 || towupper(dstPath[0]) != towupper(driveLetter_) || dstPath[1] != L':') { MM_E("Destination path {} is not on drive {}", dstPath, driveLetter_); return std::unexpected{ std::make_error_code(std::errc::invalid_argument) }; } // Open source file with overlapped I/O hSrcFile_ = ::CreateFileW(std::format(L"\\\\?\\{}", srcPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr); if (hSrcFile_ == INVALID_HANDLE_VALUE) { auto e = ::GetLastError(); MM_F("CreateFile src {} Error: {}", srcPath, mmLog::win32_message(e)); return std::unexpected{ std::error_code(e, std::system_category()) }; } // Open destination file with overlapped I/O hDstFile_ = ::CreateFileW(std::format(L"\\\\?\\{}", dstPath).c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, CREATE_ALWAYS, FILE_FLAG_OVERLAPPED, nullptr); if (hDstFile_ == INVALID_HANDLE_VALUE) { auto e = ::GetLastError(); MM_F("CreateFile dst {} Error: {}", dstPath, mmLog::win32_message(e)); CloseHandle(hSrcFile_); hSrcFile_ = INVALID_HANDLE_VALUE; return std::unexpected{ std::error_code(e, std::system_category()) }; } // Start the overlapped copy in a separate thread auto t = CreateThread(nullptr, 0, asyncOvCopy, this, 0, nullptr); if (!t) { auto e = GetLastError(); MM_F("CreateThread Error: {}", mmLog::win32_message(e)); CloseHandle(hSrcFile_); CloseHandle(hDstFile_); hSrcFile_ = INVALID_HANDLE_VALUE; hDstFile_ = INVALID_HANDLE_VALUE; return std::unexpected{ std::error_code(e, std::system_category()) }; } // Wait for the thread to complete (blocking call) WaitForSingleObject(t, INFINITE); CloseHandle(t); // Retrieve the result with mutex lock for thread safety std::lock_guard<std::mutex> lock(resultMutex_); return ovCopyResultReceiver; } void mmZeroCopy::abortCopy() { // Cancel any ongoing I/O operations if (hSrcFile_ != INVALID_HANDLE_VALUE) { CancelIoEx(hSrcFile_, nullptr); CloseHandle(hSrcFile_); hSrcFile_ = INVALID_HANDLE_VALUE; } if (hDstFile_ != INVALID_HANDLE_VALUE) { CancelIoEx(hDstFile_, nullptr); CloseHandle(hDstFile_); hDstFile_ = INVALID_HANDLE_VALUE; } // No need for async cleanup thread; handle synchronously } void mmZeroCopy::cleanup() { if (hDevNotify_) { UnregisterDeviceNotification(hDevNotify_); hDevNotify_ = nullptr; } // Reset handles if needed, but they should be managed in copy and abort if (hSrcFile_ != INVALID_HANDLE_VALUE) { CloseHandle(hSrcFile_); hSrcFile_ = INVALID_HANDLE_VALUE; } if (hDstFile_ != INVALID_HANDLE_VALUE) { CloseHandle(hDstFile_); hDstFile_ = INVALID_HANDLE_VALUE; } } DWORD WINAPI mmZeroCopy::asyncOvCopy(void* self) { reinterpret_cast<mmZeroCopy*>(self)->ovCopy(); return 0; } void mmZeroCopy::ovCopy() { // Create events for overlapped I/O HANDLE hReadEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); if (!hReadEvent) { std::lock_guard<std::mutex> lock(resultMutex_); ovCopyResultReceiver = std::unexpected{ std::error_code(GetLastError(), std::system_category()) }; return; // Early return, handles not opened yet } HANDLE hWriteEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); if (!hWriteEvent) { CloseHandle(hReadEvent); std::lock_guard<std::mutex> lock(resultMutex_); ovCopyResultReceiver = std::unexpected{ std::error_code(GetLastError(), std::system_category()) }; return; } OVERLAPPED ovRead = {0}; ovRead.hEvent = hReadEvent; OVERLAPPED ovWrite = {0}; ovWrite.hEvent = hWriteEvent; // Get source file size LARGE_INTEGER fileSize; if (!GetFileSizeEx(hSrcFile_, &fileSize)) { auto e = GetLastError(); CloseHandle(hReadEvent); CloseHandle(hWriteEvent); std::lock_guard<std::mutex> lock(resultMutex_); ovCopyResultReceiver = std::unexpected{ std::error_code(e, std::system_category()) }; return; } ULONGLONG bytesRemaining = fileSize.QuadPart; ULONGLONG offset = 0; const DWORD bufferSize = 65536; // 64KB buffer std::vector<BYTE> buffer(bufferSize); while (bytesRemaining > 0) { // Set read offset and perform overlapped read ovRead.Offset = static_cast<DWORD>(offset); ovRead.OffsetHigh = static_cast<DWORD>(offset >> 32); BOOL readResult = ReadFile(hSrcFile_, buffer.data(), static_cast<DWORD>(std::min<DWORD>(bufferSize, static_cast<DWORD>(bytesRemaining))), nullptr, &ovRead); if (!readResult && GetLastError() != ERROR_IO_PENDING) { auto e = GetLastError(); CloseHandle(hReadEvent); CloseHandle(hWriteEvent); std::lock_guard<std::mutex> lock(resultMutex_); ovCopyResultReceiver = std::unexpected{ std::error_code(e, std::system_category()) }; return; } if (!readResult) { // ERROR_IO_PENDING DWORD waitResult = WaitForSingleObject(hReadEvent, INFINITE); if (waitResult != WAIT_OBJECT_0) { auto e = GetLastError(); CancelIoEx(hSrcFile_, &ovRead); // Ensure cancellation CloseHandle(hReadEvent); CloseHandle(hWriteEvent); std::lock_guard<std::mutex> lock(resultMutex_); ovCopyResultReceiver = std::unexpected{ std::error_code(e, std::system_category()) }; return; } } DWORD bytesRead = 0; if (!GetOverlappedResult(hSrcFile_, &ovRead, &bytesRead, FALSE)) { auto e = GetLastError(); CloseHandle(hReadEvent); CloseHandle(hWriteEvent); std::lock_guard<std::mutex> lock(resultMutex_); ovCopyResultReceiver = std::unexpected{ std::error_code(e, std::system_category()) }; return; } if (bytesRead == 0) { // End of file break; } // Set write offset and perform overlapped write ovWrite.Offset = static_cast<DWORD>(offset); ovWrite.OffsetHigh = static_cast<DWORD>(offset >> 32); BOOL writeResult = WriteFile(hDstFile_, buffer.data(), bytesRead, nullptr, &ovWrite); if (!writeResult && GetLastError() != ERROR_IO_PENDING) { auto e = GetLastError(); CloseHandle(hReadEvent); CloseHandle(hWriteEvent); std::lock_guard<std::mutex> lock(resultMutex_); ovCopyResultReceiver = std::unexpected{ std::error_code(e, std::system_category()) }; return; } if (!writeResult) { // ERROR_IO_PENDING DWORD waitResult = WaitForSingleObject(hWriteEvent, INFINITE); if (waitResult != WAIT_OBJECT_0) { auto e = GetLastError(); CancelIoEx(hDstFile_, &ovWrite); CloseHandle(hReadEvent); CloseHandle(hWriteEvent); std::lock_guard<std::mutex> lock(resultMutex_); ovCopyResultReceiver = std::unexpected{ std::error_code(e, std::system_category()) }; return; } } DWORD bytesWritten = 0; if (!GetOverlappedResult(hDstFile_, &ovWrite, &bytesWritten, FALSE)) { auto e = GetLastError(); CloseHandle(hReadEvent); CloseHandle(hWriteEvent); std::lock_guard<std::mutex> lock(resultMutex_); ovCopyResultReceiver = std::unexpected{ std::error_code(e, std::system_category()) }; return; } if (bytesWritten != bytesRead) { // Partial write error (e.g., disk full) CloseHandle(hReadEvent); CloseHandle(hWriteEvent); std::lock_guard<std::mutex> lock(resultMutex_); ovCopyResultReceiver = std::unexpected{ std::error_code(ERROR_DISK_FULL, std::system_category()) }; return; } offset += bytesWritten; bytesRemaining -= bytesWritten; } // Copy completed successfully std::lock_guard<std::mutex> lock(resultMutex_); ovCopyResultReceiver = {}; // No error // Close handles and events CloseHandle(hReadEvent); CloseHandle(hWriteEvent); CloseHandle(hSrcFile_); CloseHandle(hDstFile_); hSrcFile_ = INVALID_HANDLE_VALUE; hDstFile_ = INVALID_HANDLE_VALUE; } #### `main.cpp` Demo This demo creates a simple Windows window and handles USB device events. It maintains a map of drive letters to `mmZeroCopy` instances. When a device is inserted, it starts a copy operation in a separate thread. When a device is about to be removed or is removed, it aborts the copy. The source file is fixed (e.g., `C:\\source.txt`), and the destination is created on the USB drive (e.g., `D:\\copy.txt`). ```cpp // main.cpp -- Demo for mmZeroCopy, handling multiple USB drives #include <Windows.h> #include <dbt.h> #include <string> #include <map> #include <memory> #include <format> #include "mmZeroCopy.hpp" // Include the completed mmZeroCopy header #include "mmLog.hpp" // Assume mmLog is implemented // Structure to hold application data, stored in window user data struct AppData { std::map<wchar_t, std::unique_ptr<mmZeroCopy>> driveMap; }; // Window procedure LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_DEVICECHANGE) { AppData* appData = reinterpret_cast<AppData*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)); if (!appData) return DefWindowProc(hWnd, message, wParam, lParam); DEV_BROADCAST_HDR* hdr = reinterpret_cast<DEV_BROADCAST_HDR*>(lParam); if (hdr && hdr->dbch_devicetype == DBT_DEVTYP_VOLUME) { DEV_BROADCAST_VOLUME* vol = reinterpret_cast<DEV_BROADCAST_VOLUME*>(hdr); DWORD unitmask = vol->dbcv_unitmask; // Check each drive letter (A-Z) for (int i = 0; i < 26; ++i) { if (unitmask & (1 << i)) { wchar_t driveLetter = static_cast<wchar_t>(L'A' + i); switch (wParam) { case DBT_DEVICEARRIVAL: if (appData->driveMap.find(driveLetter) == appData->driveMap.end()) { // Create mmZeroCopy instance for the drive auto copier = std::make_unique<mmZeroCopy>(hWnd, driveLetter); appData->driveMap[driveLetter] = std::move(copier); // Start copy in a separate thread to avoid blocking UI struct CopyParams { mmZeroCopy* copier; std::wstring srcPath; std::wstring dstPath; wchar_t driveLetter; }; CopyParams* params = new CopyParams{ appData->driveMap[driveLetter].get(), L"C:\\source.txt", // Fixed source file, assume it exists std::format(L"{}:\\copy.txt", driveLetter), driveLetter }; CreateThread(nullptr, 0, [](void* p) -> DWORD { CopyParams* params = static_cast<CopyParams*>(p); auto result = params->copier->copy(params->srcPath, params->dstPath); if (result) { MM_I("Copy succeeded for drive {}", params->driveLetter); } else { MM_E("Copy failed for drive {}: {}", params->driveLetter, result.error().message()); } delete params; // Clean up params return 0; }, params, 0, nullptr); } break; case DBT_DEVICEQUERYREMOVE: case DBT_DEVICEREMOVEPENDING: // Handle query or pending remove to abort copy auto it = appData->driveMap.find(driveLetter); if (it != appData->driveMap.end()) { it->second->abortCopy(); // Abort any ongoing copy } break; case DBT_DEVICEREMOVECOMPLETE: appData->driveMap.erase(driveLetter); // Remove the instance break; } } } } } else if (message == WM_DESTROY) { PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, message, wParam, lParam); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Register window class const wchar_t CLASS_NAME[] = L"mmZeroCopyWindow"; WNDCLASS wc = {}; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.lpszClassName = CLASS_NAME; RegisterClass(&wc); // Create window HWND hWnd = CreateWindowEx(0, CLASS_NAME, L"mmZeroCopy Demo", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, nullptr, nullptr, hInstance, nullptr); if (!hWnd) return 1; // Create and set AppData AppData appData; SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(&appData)); // Show window and run message loop ShowWindow(hWnd, nCmdShow); MSG msg = {}; while (GetMessage(&msg, nullptr, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; }How to Build and Run
- Dependencies: Ensure you have a C++ compiler that supports C++23 (for
std::expected) or use a polyfill. Include the Windows SDK for headers likewindows.h. AssumemmLog.hppis implemented and provides logging functions likeMM_E,MM_F,MM_I. - Compilation: Compile
mmZeroCopy.cpp,main.cpp, and link with necessary libraries (e.g.,user32.lib,kernel32.lib). - Running the Demo:
- Place a file named
source.txtinC:\(or adjust the path inmain.cpp). - Insert USB drives; the demo will attempt to copy
source.txttocopy.txton the drive. - Eject a USB drive; the demo should abort the copy and handle removal.
- Place a file named
- Handling Multiple Drives: The demo uses a map to track instances per drive letter, allowing concurrent operations on multiple USB drives.
This implementation ensures non-blocking ejection by using overlapped I/O and cancellation, while the demo handles multiple drives as requested. If you need further adjustments, let me know!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.