Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// 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...)
This solution provides a robust "zero-copy" file transfer system for Windows using memory-mapped files and asynchronous processing, ensuring that USB device ejection is not blocked.
Here's a breakdown of the completed and refactored code:
Key Changes and Improvements:
True Asynchronous copy():
copy() method now returns immediately after launching a dedicated thread for the file operation. It no longer blocks the calling thread (e.g., the UI thread).HWND provided in the constructor via a custom Windows message (WM_APP_MM_COPY_COMPLETE)."Zero-Copy" Implementation (ovCopy):
ovCopy method, which runs on a separate thread, now uses Memory-Mapped Files for the copy operation. This is often considered a form of "zero-copy" on Windows as it leverages the operating system's memory manager to move data directly between kernel buffers without explicit user-mode buffer copying.CreateFileW (for source and destination), GetFileSizeEx, CreateFileMappingW, MapViewOfFile, CopyMemory (for the actual data transfer), UnmapViewOfFile, and CloseHandle.Robust Error Handling:
std::expected<void, std::error_code> is used for function results.mmLog (assuming it's complete).__try / __except) is added around CopyMemory to gracefully handle potential access violations (e.g., if a drive is removed mid-copy).Proper Resource Management:
cleanup() method is fully implemented to release all acquired handles (file, mapping, device notification).cleanup() is called by the destructor and can be explicitly triggered by abortCopy().ovCopy() now calls cleanup() when a copy operation finishes (either successfully or with an error) to ensure resources from that specific operation are released.std::wstring for Paths:filePath_ to filePathSrc_ and introduced filePathDst_, both as std::wstring (instead of std::wstring_view). This is crucial because the asynchronous ovCopy thread outlives the copy() call, and std::wstring_view would lead to dangling pointers.abortCopy() Refinement:
CancelIoEx is called (though its effect on memory-mapped files is limited, it's good practice for general async I/O).cleanup() is launched on an asyncCleanup thread, ensuring abortCopy() returns quickly.main.cpp Demo Application:
mmZeroCopy:
mmZeroCopy with the window handle.WM_DEVICECHANGE messages to detect USB drive removal. If the source drive of an ongoing copy is removed, it automatically calls abortCopy().WM_APP_MM_COPY_COMPLETE messages to display the copy result.std::unique_ptr for mmZeroCopy and a CopyTask struct for tracking the current operation.mmZeroCopy.hpp// mmZeroCopy.hpp --Zero means zero disturb
#pragma once
#include <Windows.h>
#include <dbt.h>
#include <string>
#include <expected>
#include <system_error>
#include <format> // For std::format in C++20
// Custom message for copy completion.
// WPARAM: 1 for success, 0 for failure.
// LPARAM: Win32 error code if failure (WPARAM == 0).
#define WM_APP_MM_COPY_COMPLETE (WM_APP + 1)
// Structure to pass parameters to the asynchronous copy thread.
// Using a struct for multiple parameters is cleaner than a tuple or packed void*.
struct OvCopyParams {
class mmZeroCopy* instance;
std::wstring srcPath;
std::wstring dstPath;
};
class mmZeroCopy {
public:
using zeroCopy_r = std::expected<void, std::error_code>;
// Constructor: Registers for device notifications using the provided window handle.
mmZeroCopy(HWND hWnd);
// Destructor: Ensures all resources are cleaned up.
~mmZeroCopy();
// Initiates a zero-copy operation from `filePath` to `dstPath`.
// This method returns immediately. The operation's result (success/failure)
// will be communicated via a WM_APP_MM_COPY_COMPLETE message to `hWnd_`.
// Returns std::unexpected if the copy thread cannot be launched.
zeroCopy_r copy(const std::wstring& filePath, const std::wstring& dstPath);
// Aborts an ongoing copy operation.
// This function can be called from any thread and attempts to
// cancel any pending I/O and initiates an asynchronous cleanup.
void abortCopy();
// Cleans up all internal resources (file handles, mappings, device notifications).
// This is called by the destructor, by `abortCopy()` (asynchronously),
// and by `ovCopy()` upon its completion (either success or failure).
void cleanup();
// Returns the unit mask of the source drive involved in the most recently launched copy.
// Useful for the calling application's message loop to determine if the
// source drive of an active copy has been ejected (via WM_DEVICECHANGE).
DWORD getSourceUnitMask() const { return dbcvUnitMask_; }
private:
// Static entry point for an asynchronous cleanup thread.
// It casts `self` to `mmZeroCopy*` and calls its `cleanup()` method.
static DWORD WINAPI asyncCleanup(void* self);
// Core copy logic using memory-mapped files. This function runs on a separate thread.
// It performs the file copy and, upon completion, sets `ovCopyResultReceiver`
// and posts a `WM_APP_MM_COPY_COMPLETE` message to `hWnd_`.
void ovCopy(const std::wstring& srcPath, const std::wstring& dstPath);
// Static entry point for the asynchronous `ovCopy` thread.
// It casts `params` to `OvCopyParams*`, extracts the instance and paths,
// then calls the non-static `ovCopy` method. It takes ownership of `params`.
static DWORD WINAPI asyncOvCopy(void* params);
HWND hWnd_{nullptr}; // Window handle for device notifications and message posting.
HDEVNOTIFY hDevNotify_{nullptr}; // Handle for the device notification registration.
std::wstring filePathSrc_{}; // Stores the source file path for the current copy.
std::wstring filePathDst_{}; // Stores the destination file path for the current copy.
DWORD dbcvUnitMask_{0}; // Unit mask of the source drive (e.g., 1 for A:, 2 for B:, 4 for C:).
// Handles for the source and destination files and their memory mappings.
HANDLE hFileSrc_{INVALID_HANDLE_VALUE};
HANDLE hFileDst_{INVALID_HANDLE_VALUE};
HANDLE hMapSrc_{nullptr};
HANDLE hMapDst_{nullptr};
// Used internally by `ovCopy` to store its result before posting the message.
// Not directly accessed by `copy()` after refactoring.
zeroCopy_r ovCopyResultReceiver{};
};
mmZeroCopy.cpp// mmZeroCopy.cpp
#include "mmZeroCopy.h"
#include "mmLog.hpp" // Assumed to provide MM_I, MM_W, MM_E, MM_F, mmLog::last_error(), mmLog::Logger::win32_message
#include <string_view> // Useful for some mmLog functions if they take views
#include <locale> // For std::toupper
// Helper function to extract the drive letter from a path.
// Returns 0 if the path does not start with a drive letter (e.g., C:).
static wchar_t get_drive_letter(const std::wstring& path) {
if (path.length() >= 2 && path[1] == L':') {
// Use std::toupper for locale-independent uppercase conversion.
return static_cast<wchar_t>(std::toupper(static_cast<wint_t>(path[0]), std::locale()));
}
return 0; // Not a drive path
}
// Constructor: Initializes the mmZeroCopy instance.
mmZeroCopy::mmZeroCopy(HWND hWnd) : hWnd_(hWnd) {
DEV_BROADCAST_VOLUME dbcvFilter{};
dbcvFilter.dbcv_size = sizeof(dbcvFilter);
dbcvFilter.dbcv_devicetype = DBT_DEVTYP_VOLUME;
// Register for device notifications for all volume changes (arrival/removal).
// This allows the associated window to receive WM_DEVICECHANGE messages.
hDevNotify_ = ::RegisterDeviceNotificationW(hWnd_, &dbcvFilter, DEVICE_NOTIFY_WINDOW_HANDLE);
if (!hDevNotify_) {
// Log a fatal error and throw an exception if registration fails.
// This indicates a critical initialization issue.
MM_F("RegisterDeviceNotification Error: {}", mmLog::last_error());
throw std::runtime_error("mmZeroCopy: init failed");
}
MM_I("mmZeroCopy initialized. Device notifications registered for HWND: {}", (void*)hWnd_);
}
// Destructor: Ensures all resources are properly released when the object is destroyed.
mmZeroCopy::~mmZeroCopy() {
cleanup(); // Call cleanup to release all handles and unregister notifications.
MM_I("mmZeroCopy destroyed.");
}
// Cleans up all internal resources.
// This method is designed to be safe to call multiple times, as it checks
// if handles are valid before attempting to close them.
void mmZeroCopy::cleanup() {
// Unregister device notification if it was successfully registered.
if (hDevNotify_) {
if (!::UnregisterDeviceNotification(hDevNotify_)) {
MM_E("UnregisterDeviceNotification Error: {}", mmLog::last_error());
}
hDevNotify_ = nullptr; // Reset the handle to avoid double-free.
MM_I("Device notifications unregistered.");
}
// Unmap memory views first to flush any pending writes and release virtual memory.
// No need to check pSrc/pDst explicitly here, as they are local to ovCopy.
// However, if we tracked them as members, they'd be unmapped here.
// For this design, UnmapViewOfFile is called within ovCopy.
// Close file mappings.
if (hMapSrc_) {
if (!::CloseHandle(hMapSrc_)) {
MM_E("CloseHandle(hMapSrc_) Error: {}", mmLog::last_error());
}
hMapSrc_ = nullptr;
}
if (hMapDst_) {
if (!::CloseHandle(hMapDst_)) {
MM_E("CloseHandle(hMapDst_) Error: {}", mmLog::last_error());
}
hMapDst_ = nullptr;
}
// Close file handles.
if (hFileSrc_ != INVALID_HANDLE_VALUE) {
if (!::CloseHandle(hFileSrc_)) {
MM_E("CloseHandle(hFileSrc_) Error: {}", mmLog::last_error());
}
hFileSrc_ = INVALID_HANDLE_VALUE;
}
if (hFileDst_ != INVALID_HANDLE_VALUE) {
if (!::CloseHandle(hFileDst_)) {
MM_E("CloseHandle(hFileDst_) Error: {}", mmLog::last_error());
}
hFileDst_ = INVALID_HANDLE_VALUE;
}
// Clear stored paths and unit mask.
filePathSrc_.clear();
filePathDst_.clear();
dbcvUnitMask_ = 0;
MM_I("mmZeroCopy cleanup completed.");
}
// Initiates the copy operation by launching an asynchronous thread.
// Returns immediately; the actual copy runs in the background.
mmZeroCopy::zeroCopy_r mmZeroCopy::copy(const std::wstring& filePath, const std::wstring& dstPath) {
// Store source and destination paths. It's crucial to copy the strings
// because the async thread will outlive this function call.
filePathSrc_ = filePath;
filePathDst_ = dstPath;
// Determine the source drive's unit mask. This is used by the main application
// to check if the drive being ejected corresponds to the source of the current copy.
wchar_t drive = get_drive_letter(filePathSrc_);
if (drive == 0) {
MM_E("Invalid source file path (no drive letter): {}", filePathSrc_);
return std::unexpected { std::make_error_code(std::errc::invalid_argument) };
}
dbcvUnitMask_ = 1u << (drive - L'A');
MM_I("Copy requested: '{}' to '{}'. Source drive unit mask: {:#x}", filePathSrc_, filePathDst_, dbcvUnitMask_);
// Allocate parameters for the asynchronous thread.
// The thread will take ownership of this memory and delete it upon completion.
auto* params = new OvCopyParams{this, filePathSrc_, filePathDst_};
if (!params) {
MM_E("Failed to allocate OvCopyParams for async thread.");
return std::unexpected { std::make_error_code(std::errc::not_enough_memory) };
}
// Create the thread that will execute the `ovCopy` logic.
HANDLE hThread = CreateThread(nullptr, 0, asyncOvCopy, params, 0, nullptr);
if (!hThread) {
auto e = ::GetLastError();
MM_E("CreateThread for asyncOvCopy Error: {} ({})", mmLog::Logger::win32_message(e), e);
delete params; // Clean up `params` if thread creation fails.
return std::unexpected { std::error_code(e, std::system_category()) };
}
// Close the thread handle immediately. We don't need to wait for it,
// as it signals completion via a message to `hWnd_`.
CloseHandle(hThread);
MM_I("Async copy thread launched successfully.");
return {}; // Return success immediately; the copy operation is now running in the background.
}
// Aborts an ongoing copy operation.
// This function attempts to cancel any pending I/O and then initiates an
// asynchronous cleanup of resources.
void mmZeroCopy::abortCopy() {
MM_W("Aborting copy operation for source: '{}'...", filePathSrc_);
// Attempt to cancel any pending I/O operations on the file handles.
// While memory-mapped files use `CopyMemory` which isn't directly cancelable
// by `CancelIoEx`, it's good practice for general async I/O and might
// help close underlying file handles if they're used for other purposes.
if (hFileSrc_ != INVALID_HANDLE_VALUE) {
::CancelIoEx(hFileSrc_, nullptr);
MM_W("CancelIoEx called on hFileSrc_.");
}
if (hFileDst_ != INVALID_HANDLE_VALUE) {
::CancelIoEx(hFileDst_, nullptr);
MM_W("CancelIoEx called on hFileDst_.");
}
// Launch cleanup on a separate thread to ensure `abortCopy()` returns quickly
// and doesn't block the caller (e.g., the UI thread responding to a device removal).
// The cleanup will then ensure all handles are closed.
HANDLE hThread = CreateThread(nullptr, 0, asyncCleanup, this, 0, nullptr);
if (hThread) {
CloseHandle(hThread); // Don't wait for cleanup, just launch it.
MM_W("Async cleanup thread launched for abort.");
} else {
// Fallback: If thread creation fails, perform cleanup synchronously.
MM_E("Failed to launch asyncCleanup thread during abortCopy: {}", mmLog::last_error());
cleanup();
}
}
// Static entry point for the asynchronous cleanup thread.
DWORD WINAPI mmZeroCopy::asyncCleanup(void* self) {
// Cast the void* parameter back to mmZeroCopy* and call its cleanup method.
auto* pThis = static_cast<mmZeroCopy*>(self);
if (pThis) {
pThis->cleanup();
MM_I("Async cleanup completed on dedicated thread.");
} else {
MM_E("asyncCleanup received a null 'this' pointer.");
}
return 0;
}
// Core copy logic using memory-mapped files. This runs on a separate thread.
void mmZeroCopy::ovCopy(const std::wstring& srcPath, const std::wstring& dstPath) {
ovCopyResultReceiver = {}; // Reset the result for the current operation.
MM_I("Starting memory-mapped copy from '{}' to '{}'.", srcPath, dstPath);
const void* pSrc = nullptr; // Pointer to mapped source view
void* pDst = nullptr; // Pointer to mapped destination view
// Use a goto for structured cleanup on error, common in Win32 API.
// Alternatively, C++ RAII wrappers for handles could be used.
// 1. Open Source File
hFileSrc_ = ::CreateFileW(
(L"\\\\?\\" + srcPath).c_str(), // Use \\?\ prefix for long paths
GENERIC_READ, // Open for reading
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, // Allow other processes to access the file
nullptr, // Default security attributes
OPEN_EXISTING, // File must exist
FILE_ATTRIBUTE_NORMAL, // Normal file attributes
nullptr); // No template file
if (hFileSrc_ == INVALID_HANDLE_VALUE) {
auto e = ::GetLastError();
MM_E("CreateFile (source) '{}' Error: {} ({})", srcPath, mmLog::Logger::win32_message(e), e);
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
goto end_copy;
}
// Get source file size.
LARGE_INTEGER fileSize;
if (!::GetFileSizeEx(hFileSrc_, &fileSize)) {
auto e = ::GetLastError();
MM_E("GetFileSizeEx '{}' Error: {} ({})", srcPath, mmLog::Logger::win32_message(e), e);
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
goto end_copy;
}
if (fileSize.QuadPart == 0) {
MM_W("Source file '{}' is empty. Creating empty destination file.", srcPath);
// Special case: For an empty file, just create an empty destination file.
hFileDst_ = ::CreateFileW(
(L"\\\\?\\" + dstPath).c_str(),
GENERIC_WRITE, // Open for writing
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr,
CREATE_ALWAYS, // Create new or overwrite existing
FILE_ATTRIBUTE_NORMAL,
nullptr);
if (hFileDst_ == INVALID_HANDLE_VALUE) {
auto e = ::GetLastError();
MM_E("CreateFile (destination for empty file) '{}' Error: {} ({})", dstPath, mmLog::Logger::win32_message(e), e);
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
} else {
MM_I("Empty file '{}' copied to '{}'.", srcPath, dstPath);
}
goto end_copy; // Exit after handling empty file.
}
// 2. Create Source File Mapping (Memory mapping the source file for reading)
hMapSrc_ = ::CreateFileMappingW(
hFileSrc_, // Handle to the file to map
nullptr, // Default security attributes
PAGE_READONLY, // Read-only access to the mapped memory
0, 0, // Map the entire file (size)
nullptr); // No name for the mapping object
if (!hMapSrc_) {
auto e = ::GetLastError();
MM_E("CreateFileMapping (source) '{}' Error: {} ({})", srcPath, mmLog::Logger::win32_message(e), e);
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
goto end_copy;
}
// 3. Map Source File View (Get a pointer to the mapped memory)
pSrc = ::MapViewOfFile(
hMapSrc_, // Handle to the file mapping object
FILE_MAP_READ, // Read access to the view
0, 0, // Map from the beginning of the file (offset)
0); // Map the entire file (size)
if (!pSrc) {
auto e = ::GetLastError();
MM_E("MapViewOfFile (source) '{}' Error: {} ({})", srcPath, mmLog::Logger::win32_message(e), e);
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
goto end_copy;
}
// 4. Create/Open Destination File
hFileDst_ = ::CreateFileW(
(L"\\\\?\\" + dstPath).c_str(),
GENERIC_READ | GENERIC_WRITE, // Need read/write access for mapping
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr,
CREATE_ALWAYS, // Create new file, overwrite if exists
FILE_ATTRIBUTE_NORMAL,
nullptr);
if (hFileDst_ == INVALID_HANDLE_VALUE) {
auto e = ::GetLastError();
MM_E("CreateFile (destination) '{}' Error: {} ({})", dstPath, mmLog::Logger::win32_message(e), e);
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
goto end_copy;
}
// Set the destination file size to match the source file size.
// This is crucial before creating a writable file mapping for the destination.
LARGE_INTEGER currentPos;
currentPos.QuadPart = fileSize.QuadPart;
if (!::SetFilePointerEx(hFileDst_, currentPos, nullptr, FILE_BEGIN)) {
auto e = ::GetLastError();
MM_E("SetFilePointerEx (destination) '{}' Error: {} ({})", dstPath, mmLog::Logger::win32_message(e), e);
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
goto end_copy;
}
if (!::SetEndOfFile(hFileDst_)) {
auto e = ::GetLastError();
MM_E("SetEndOfFile (destination) '{}' Error: {} ({})", dstPath, mmLog::Logger::win32_message(e), e);
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
goto end_copy;
}
// 5. Create Destination File Mapping
hMapDst_ = ::CreateFileMappingW(
hFileDst_, // Handle to the destination file
nullptr, // Default security attributes
PAGE_READWRITE, // Read/write access for the mapped memory
fileSize.HighPart, fileSize.LowPart, // Size of the mapping (must match file size)
nullptr); // No name
if (!hMapDst_) {
auto e = ::GetLastError();
MM_E("CreateFileMapping (destination) '{}' Error: {} ({})", dstPath, mmLog::Logger::win32_message(e), e);
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
goto end_copy;
}
// 6. Map Destination File View
pDst = ::MapViewOfFile(
hMapDst_, // Handle to the destination file mapping object
FILE_MAP_WRITE, // Write access to the view
0, 0,
0);
if (!pDst) {
auto e = ::GetLastError();
MM_E("MapViewOfFile (destination) '{}' Error: {} ({})", dstPath, mmLog::Logger::win32_message(e), e);
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
goto end_copy;
}
// 7. Perform the memory copy using CopyMemory (equivalent to memcpy, but potentially optimized)
// Use __try/__except to catch access violations which can occur if the underlying
// file/drive is removed while memory is being accessed.
__try {
MM_I("Performing memory copy for {} bytes from source to destination...", fileSize.QuadPart);
::CopyMemory(pDst, pSrc, fileSize.QuadPart);
MM_I("Memory copy completed.");
} __except (EXCEPTION_EXECUTE_HANDLER) {
// This block is executed if an exception (like an access violation) occurs.
// GetLastError might not be directly set by CopyMemory, but it's good practice to check.
auto e = ::GetLastError();
MM_F("Memory copy EXCEPTION for '{}' to '{}'. Error: {} ({})", srcPath, dstPath, mmLog::Logger::win32_message(e), e);
// Set a specific error code to indicate an aborted/interrupted operation.
ovCopyResultReceiver = std::unexpected { std::error_code(ERROR_ABANDONED_WAIT_0, std::system_category()) };
// Ensure views are unmapped even if an exception occurred.
if (pSrc) { ::UnmapViewOfFile(pSrc); pSrc = nullptr; }
if (pDst) { ::UnmapViewOfFile(pDst); pDst = nullptr; }
goto end_copy; // Jump to cleanup and message posting.
}
// 8. Unmap views. This flushes cached data to disk and releases virtual memory.
// Explicit unmapping is good practice for timely resource release, though
// views are automatically unmapped when the corresponding mapping handles are closed.
if (pDst) {
if (!::UnmapViewOfFile(pDst)) {
auto e = ::GetLastError();
MM_E("UnmapViewOfFile (destination) Error: {} ({})", mmLog::Logger::win32_message(e), e);
// If destination unmap fails, it's an issue. Mark as failed.
if (ovCopyResultReceiver.has_value()) { // Only set if not already failed
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
}
}
pDst = nullptr; // Mark as unmapped
}
if (pSrc) {
if (!::UnmapViewOfFile(pSrc)) {
auto e = ::GetLastError();
MM_E("UnmapViewOfFile (source) Error: {} ({})", mmLog::Logger::win32_message(e), e);
// If source unmap fails, it's an issue. Mark as failed.
if (ovCopyResultReceiver.has_value()) { // Only set if not already failed
ovCopyResultReceiver = std::unexpected { std::error_code(e, std::system_category()) };
}
}
pSrc = nullptr; // Mark as unmapped
}
MM_I("File '{}' copied to '{}' successfully (result receiver: {}).", srcPath, dstPath, ovCopyResultReceiver.has_value() ? "success" : "failure");
end_copy:
// Post a message to the associated window to signal completion.
// The main thread's message loop will process this.
WPARAM wparam = ovCopyResultReceiver.has_value() ? 1 : 0; // 1 for success, 0 for failure
LPARAM lparam = 0;
if (!ovCopyResultReceiver.has_value()) {
lparam = static_cast<LPARAM>(ovCopyResultReceiver.error().value()); // Send Win32 error code
MM_E("Copy operation failed for '{}'. Error: {} ({})", srcPath, mmLog::Logger::win32_message(lparam), lparam);
} else {
MM_I("Copy operation completed successfully for '{}'.", srcPath);
}
if (hWnd_) {
::PostMessageW(hWnd_, WM_APP_MM_COPY_COMPLETE, wparam, lparam);
} else {
MM_E("hWnd_ is null, cannot post copy completion message for '{}'.", srcPath);
}
// Call cleanup to release all handles (file and mapping) that were opened
// during this `ovCopy` call. This is safe as `copy()` returns immediately,
// and `abortCopy()`'s cleanup is also asynchronous.
cleanup();
}
// Static entry point for the asynchronous copy thread.
// This function bridges the Windows API thread creation mechanism to the C++ member function.
DWORD WINAPI mmZeroCopy::asyncOvCopy(void* params) {
auto* ovParams = static_cast<OvCopyParams*>(params);
if (!ovParams) {
MM_E("asyncOvCopy received null parameters.");
return 1; // Indicate error
}
mmZeroCopy* pThis = ovParams->instance;
// Copy the paths from the heap-allocated structure to local std::wstring variables.
// Use std::move to efficiently transfer ownership of string data.
std::wstring srcPath = std::move(ovParams->srcPath);
std::wstring dstPath = std::move(ovParams->dstPath);
// Delete the heap-allocated parameters structure as its contents have been moved.
delete ovParams;
if (pThis) {
pThis->ovCopy(srcPath, dstPath); // Call the actual copy logic.
} else {
MM_E("asyncOvCopy 'this' pointer is null, cannot perform copy.");
}
return 0; // Indicate success
}
mmLog.hpp (Simple Placeholder for Demo)// mmLog.hpp (Simple placeholder for the demo)
#pragma once
#include <iostream>
#include <string>
#include <system_error>
#include <format> // Requires C++20 for std::format
#include <Windows.h>
namespace mmLog {
class Logger {
public:
// Basic logging function that formats and prints messages to console.
template<typename... Args>
static void log(const std::string& level, const std::string& format_str, Args&&... args) {
std::string msg;
try {
// Use std::vformat for runtime formatting.
msg = std::vformat(format_str, std::make_format_args(std::forward<Args>(args)...));
} catch (const std::exception& e) {
// Fallback for formatting errors
msg = std::format("Failed to format log message: {} | Original: {}", e.what(), format_str);
}
std::cout << "[" << level << "] " << msg << std::endl;
}
// Retrieves the system error message for a given Win32 error code.
static std::string win32_message(DWORD error_code) {
LPWSTR buffer = nullptr;
DWORD chars = FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPWSTR)&buffer,
0,
nullptr
);
std::string message;
if (chars > 0) {
// Convert WCHAR buffer to std::string (UTF-8).
int size_needed = WideCharToMultiByte(CP_UTF8, 0, buffer, chars, nullptr, 0, nullptr, nullptr);
if (size_needed > 0) {
message.resize(size_needed);
WideCharToMultiByte(CP_UTF8, 0, buffer, chars, message.data(), size_needed, nullptr, nullptr);
}
LocalFree(buffer); // Free the buffer allocated by FormatMessageW.
} else {
message = std::format("Unknown error ({})", error_code);
}
// Remove trailing newlines/carriage returns from FormatMessageW output
if (!message.empty() && (message.back() == '\n' || message.back() == '\r')) {
message.pop_back();
}
if (!message.empty() && (message.back() == '\n' || message.back() == '\r')) {
message.pop_back();
}
return message;
}
};
// Helper to get the last Win32 error as a std::error_code.
inline std::error_code last_error() {
return std::error_code(::GetLastError(), std::system_category());
}
}
// Convenience macros for different log levels.
#define MM_I(format_str, ...) mmLog::Logger::log("INFO", format_str, __VA_ARGS__)
#define MM_W(format_str, ...) mmLog::Logger::log("WARN", format_str, __VA_ARGS__)
#define MM_E(format_str, ...) mmLog::Logger::log("ERROR", format_str, __VA_ARGS__)
#define MM_F(format_str, ...) mmLog::Logger::log("FATAL", format_str, __VA_ARGS__)
main.cpp (Caller Demo)// main.cpp
#include "mmZeroCopy.h"
#include "mmLog.hpp" // Include our simple logging utility
#include <iostream>
#include <thread> // For std::this_thread::sleep_for
#include <chrono> // For std::chrono::milliseconds
#include <vector>
#include <map>
#include <set>
#include <memory> // For std::unique_ptr
// Global variables to manage the window and the mmZeroCopy instance.
// Using std::unique_ptr ensures proper cleanup via RAII.
HWND g_hWnd = nullptr;
std::unique_ptr<mmZeroCopy> g_zeroCopyInstance;
// Structure to keep track of the current copy task.
// For this demo, we assume only one active copy operation per mmZeroCopy instance.
struct CopyTask {
std::wstring srcPath;
std::wstring dstPath;
DWORD sourceDriveMask; // Unit mask of the source drive, for device change checks.
};
std::unique_ptr<CopyTask> g_currentCopyTask = nullptr; // Tracks the currently active copy.
// Forward declaration for the main window procedure.
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
// Entry point for the Windows application.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// 1. Create a dummy hidden window to receive Windows messages (especially device notifications).
const wchar_t CLASS_NAME[] = L"mmZeroCopyDemoClass";
WNDCLASSEXW wc = {};
wc.cbSize = sizeof(WNDCLASSEXW);
wc.lpfnWndProc = WindowProc; // Our message handling function.
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
if (!RegisterClassExW(&wc)) {
MM_F("Failed to register window class: {}", mmLog::last_error());
return 1;
}
g_hWnd = CreateWindowExW(
0, // Optional window style
CLASS_NAME, // Window class name
L"mmZeroCopy Demo Window", // Window title (can be hidden, but useful for debugging)
WS_OVERLAPPEDWINDOW, // Basic window style
CW_USEDEFAULT, CW_USEDEFAULT, // Default position
400, 300, // Default size
nullptr, // No parent window
nullptr, // No menu
hInstance, // Instance handle
nullptr // No additional application data
);
if (g_hWnd == nullptr) {
MM_F("Failed to create window: {}", mmLog::last_error());
return 1;
}
// ShowWindow(g_hWnd, nCmdShow); // Keep window hidden for a console-like demo.
// UpdateWindow(g_hWnd); // Don't update if hidden.
MM_I("Dummy window created. HWND: {}", (void*)g_hWnd);
// 2. Initialize mmZeroCopy with the window handle.
try {
g_zeroCopyInstance = std::make_unique<mmZeroCopy>(g_hWnd);
} catch (const std::runtime_error& e) {
MM_F("Failed to initialize mmZeroCopy: {}", e.what());
return 1;
}
MM_I("Demo ready. Press 'C' to start a copy, 'A' to abort. Try unplugging the source drive during copy.");
MM_I("Please configure source and destination paths in main.cpp to valid locations on your system.");
MM_I("Example paths are commented out inside WM_KEYDOWN 'C' handler.");
// 3. Main message loop: processes Windows messages, including device notifications
// and custom copy completion messages.
MSG msg = {};
while (GetMessage(&msg, nullptr, 0, 0)) {
TranslateMessage(&msg); // Translate virtual-key messages into character messages.
DispatchMessage(&msg); // Dispatch message to WindowProc.
}
// Explicitly destroy the mmZeroCopy instance before exiting.
// std::unique_ptr will call the destructor, which calls cleanup().
g_zeroCopyInstance.reset();
MM_I("Application exiting.");
return 0;
}
// Window Procedure: Handles messages sent to our dummy window.
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_CREATE: {
MM_I("WM_CREATE received by demo window.");
// Initial setup or informational messages.
break;
}
case WM_KEYDOWN: {
// Handle keyboard input for demo purposes.
if (wParam == 'C') { // Press 'C' key to initiate a copy.
MM_I("'C' key pressed. Attempting to start a copy.");
if (g_currentCopyTask) {
MM_W("A copy is already in progress. Aborting current one before starting new.");
g_zeroCopyInstance->abortCopy();
g_currentCopyTask.reset(); // Clear the current task tracker.
// Give a moment for abort to process and resources to clean up.
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
// --- IMPORTANT: Configure these paths to actual files on your system! ---
// For example:
// std::wstring sourcePath = L"E:\\Videos\\LargeVideo.mp4"; // A file on a USB drive (E:).
// std::wstring destPath = L"C:\\Temp\\CopiedVideo.mp4"; // A destination on your local C: drive.
// Or:
// std::wstring sourcePath = L"C:\\Users\\Public\\Videos\\Sample Videos\\Wildlife.wmv";
// std::wstring destPath = L"D:\\Wildlife_copy.wmv";
std::wstring sourcePath = L"C:\\Users\\Public\\Videos\\Sample Videos\\Wildlife.wmv"; // <--- !!! REPLACE WITH YOUR SOURCE PATH !!!
std::wstring destPath = L"D:\\Wildlife_copy.wmv"; // <--- !!! REPLACE WITH YOUR DESTINATION PATH !!!
if (sourcePath.empty() || destPath.empty()) {
MM_E("Source or destination path is empty. Please set valid paths in main.cpp.");
break;
}
MM_I("Attempting copy from '{}' to '{}'.", sourcePath, destPath);
// Call the copy method, which returns immediately.
auto result = g_zeroCopyInstance->copy(sourcePath, destPath);
if (result.has_value()) {
// If the copy operation was successfully launched, track it.
g_currentCopyTask = std::make_unique<CopyTask>();
g_currentCopyTask->srcPath = sourcePath;
g_currentCopyTask->dstPath = destPath;
g_currentCopyTask->sourceDriveMask = g_zeroCopyInstance->getSourceUnitMask();
MM_I("Copy operation successfully launched. Waiting for completion message...");
} else {
// If `copy` itself failed to launch the thread/open files.
MM_E("Failed to launch copy operation: {} ({})", mmLog::Logger::win32_message(result.error().value()), result.error().value());
}
} else if (wParam == 'A') { // Press 'A' key to abort a copy.
MM_I("'A' key pressed. Attempting to abort current copy.");
if (g_currentCopyTask) {
g_zeroCopyInstance->abortCopy();
g_currentCopyTask.reset(); // Clear the current task tracker.
MM_I("Copy operation aborted (if active).");
} else {
MM_I("No active copy to abort.");
}
}
break;
}
case WM_DEVICECHANGE: {
// Handle device change notifications (e.g., USB drive plug/unplug).
if (wParam == DBT_DEVICEREMOVECOMPLETE || wParam == DBT_DEVICEARRIVAL) {
auto* hdr = reinterpret_cast<DEV_BROADCAST_HDR*>(lParam);
if (hdr && hdr->dbcd_devicetype == DBT_DEVTYP_VOLUME) {
auto* dbcv = reinterpret_cast<DEV_BROADCAST_VOLUME*>(hdr);
MM_I("WM_DEVICECHANGE: Volume event detected for UnitMask: {:#x}. Event: {}",
dbcv->dbcv_unitmask,
(wParam == DBT_DEVICEREMOVECOMPLETE ? "REMOVED" : "ARRIVED"));
if (wParam == DBT_DEVICEREMOVECOMPLETE) {
// If a volume was removed, check if it's the source drive for our active copy.
if (g_currentCopyTask && (dbcv->dbcv_unitmask & g_currentCopyTask->sourceDriveMask)) {
MM_W("Source drive for current copy ('{}') removed! Aborting copy.", g_currentCopyTask->srcPath);
g_zeroCopyInstance->abortCopy();
g_currentCopyTask.reset(); // Mark copy as no longer active.
} else if (g_currentCopyTask) {
MM_I("Another volume removed, but not the source for current copy.");
} else {
MM_I("Volume removed, but no active copy being tracked.");
}
}
}
}
break;
}
case WM_APP_MM_COPY_COMPLETE: {
// Custom message handler for copy completion.
bool success = (wParam != 0); // WPARAM 1 means success, 0 means failure.
DWORD errorCode = static_cast<DWORD>(lParam); // LPARAM carries the Win32 error code on failure.
MM_I("WM_APP_MM_COPY_COMPLETE received. Copy Success: {}", success ? "YES" : "NO");
if (g_currentCopyTask) {
if (success) {
MM_I("Copy of '{}' to '{}' COMPLETED successfully.", g_currentCopyTask->srcPath, g_currentCopyTask->dstPath);
} else {
MM_E("Copy of '{}' to '{}' FAILED with error: {} ({})",
g_currentCopyTask->srcPath, g_currentCopyTask->dstPath,
mmLog::Logger::win32_message(errorCode), errorCode);
}
g_currentCopyTask.reset(); // Copy task is now finished, clear tracking.
} else {
MM_W("WM_APP_MM_COPY_COMPLETE received but no active copy task was tracked.");
}
break;
}
case WM_DESTROY: {
MM_I("WM_DESTROY received by demo window. Posting quit message.");
PostQuitMessage(0); // Terminates the message loop.
break;
}
default:
// Let Windows handle any messages we don't explicitly process.
return DefWindowProcW(hWnd, uMsg, wParam, lParam);
}
return 0;
}
Save the files:
mmZeroCopy.hppmmZeroCopy.cppmmLog.hppmain.cppEnsure C++20 Standard: The code uses std::format which requires C++20.
Compile with Visual Studio (or g++ on MinGW/MSYS2):
Visual Studio (recommended):
.cpp and .hpp files to the project.main.cpp is set up for WINDOWS subsystem by default because of WinMain).#include <Windows.h> and link against user32.lib for windowing and advapi32.lib for FormatMessageW if not linked by default. (These are usually linked by default for Windows projects).g++ (MinGW/MSYS2):
g++ -std=c++20 mmZeroCopy.cpp main.cpp -o mmZeroCopyDemo.exe -luser32 -ladvapi32 -ldbntwin -static-libstdc++ -static-libgcc
(Note: dbntwin might not be strictly needed, but dbt.h relates to device broadcast notifications. -static-libstdc++ and -static-libgcc are for easier distribution.)
Run the Executable:
CONSOLE subsystem) or just run the .exe.sourcePath and destPath variables in main.cpp (within the WM_KEYDOWN 'C' handler) to valid paths on your system before compiling.WM_DEVICECHANGE handling and copy abortion. The console output will show the logging messages.This setup provides a complete and functional demonstration of a non-blocking, "zero-copy" file system using Windows APIs.