以下内容全部来自www.vbasm.com 中的WIN64驱动编程基础教程

1.文件复制

  1 BOOLEAN ZwCopyFile
  2 (
  3 IN PUNICODE_STRING ustrDestFile, // \??\c:\1.txt
  4 IN PUNICODE_STRING ustrSrcFile // \??\c:\0.txt
  5 ) {
  6 HANDLE hSrcFile, hDestFile;
  7 PVOID buffer = NULL;
  8 ULONG length = 0;
  9 LARGE_INTEGER offset = {0};
 10 IO_STATUS_BLOCK Io_Status_Block = {0};
 11 OBJECT_ATTRIBUTES obj_attrib;
 12 NTSTATUS status;
 13 BOOLEAN bRet = FALSE;
 14 do
 15 {
 16 // 打开源文件
 17 InitializeObjectAttributes( &obj_attrib,
 18 ustrSrcFile,
 19 OBJ_CASE_INSENSITIVE |
 20 OBJ_KERNEL_HANDLE,
 21 NULL,
 22 NULL);
 23 status = ZwCreateFile( &hSrcFile,
 24 GENERIC_READ,
 25 &obj_attrib,
 26 &Io_Status_Block,
 27 NULL,
 28 FILE_ATTRIBUTE_NORMAL,
 29 FILE_SHARE_READ,
 30 FILE_OPEN,
 31 FILE_NON_DIRECTORY_FILE |
 32 FILE_SYNCHRONOUS_IO_NONALERT,
 33 NULL,
 34 0 );
 35 if (!NT_SUCCESS(status))
 36 {
 37 bRet = FALSE;
 38 goto END;
 39 }
 40 // 打开目标文件
 41 InitializeObjectAttributes( &obj_attrib,
 42 ustrDestFile,
 43 OBJ_CASE_INSENSITIVE |
 44 OBJ_KERNEL_HANDLE,
 45 NULL,
 46 NULL);
 47 status = ZwCreateFile( &hDestFile,
 48 GENERIC_WRITE,
 49 &obj_attrib,
 50 &Io_Status_Block,
 51 NULL,
 52 FILE_ATTRIBUTE_NORMAL,
 53 FILE_SHARE_READ,
 54 FILE_OPEN_IF,
 55 FILE_NON_DIRECTORY_FILE |
 56 FILE_SYNCHRONOUS_IO_NONALERT,
 57 NULL,
 58 0 );
 59 if (!NT_SUCCESS(status))
 60 {
 61 bRet = FALSE;
 62 goto END;
 63 }
 64 // 为 buffer 分配 4KB 空间
 65 buffer = ExAllocatePool(NonPagedPool, 1024 * 4);
 66 if (buffer == NULL)
 67 {
 68 bRet = FALSE;
 69 goto END;
 70 }
 71 // 复制文件
 72 while (1)
 73 {
 74 length = 4 * 1024;
 75 // 读取源文件
 76 status = ZwReadFile(hSrcFile,
 77 NULL,
 78 NULL,
 79 NULL,
 80 &Io_Status_Block,
 81 buffer,
 82 length,
 83 &offset,
 84 NULL);
 85 if (!NT_SUCCESS(status))
 86 {
 87 // 如果状态为 STATUS_END_OF_FILE,说明文件已经读取到末尾
 88 if (status == STATUS_END_OF_FILE)
 89 {
 90 bRet = TRUE;
 91 goto END;
 92 }
 93 }
 94 // 获得实际读取的长度
 95 length = (ULONG)Io_Status_Block.Information;
 96 // 写入到目标文件
 97 status = ZwWriteFile( hDestFile,
 98 NULL,
 99 NULL,
100 NULL,
101 &Io_Status_Block,
102 buffer,
103 length,
104 &offset,
105 NULL);
106 if (!NT_SUCCESS(status))
107 {
108 bRet = FALSE;
109 goto END;
110 }
111 // 移动文件指针
112 offset.QuadPart += length;
113 }
114 }
115 while (0);
116 END:
117 if (hSrcFile)
118 {
119 ZwClose(hSrcFile);
120 }
121 if (hDestFile)
122 {
123 ZwClose(hDestFile);
124 }
125 if (buffer != NULL)
126 {
127 ExFreePool(buffer);
128 }
129 return bRet;
130 }