1 //CreateDevice.c
2 //2016.07.14
3
4 #include "ntddk.h"
5
6 //驱动卸载函数Self
7 VOID MyDriverUnload(PDRIVER_OBJECT pDriverObject)
8 {
9 UNICODE_STRING usSymName;
10 RtlInitUnicodeString(&usSymName, L"\\??\\FirstDevice");
11
12 //先删除符号链接,后删除设备对象
13 if (pDriverObject->DeviceObject != NULL)
14 {
15 IoDeleteSymbolicLink(&usSymName); //删除符号链接
16 IoDeleteDevice(pDriverObject->DeviceObject); //删除设备对象
17 KdPrint(("Delete Device Sucess."));
18 }
19 }
20
21 //创建设备函数Self
22 NTSTATUS CreateDevice(PDRIVER_OBJECT pDriverObject)
23 {
24 NTSTATUS Status;
25 UNICODE_STRING usDevName;
26 UNICODE_STRING usSymName;
27 PDEVICE_OBJECT pDevObj; //设备对象,用于指向创建的设备
28
29 //DDK API 为UNICODE_STRING赋值的函数
30 RtlInitUnicodeString(&usDevName, L"\\Device\\FirstDevice");
31
32 //创建设备函数API 创建设备"\\Device\\FirstDevice"
33 //设备创建后,会返回给pDevObj,同时给pDriverObject->DeviceObject赋值
34 //The IoCreateDevice routine creates a device object for use by a driver.
35 /*
36 NTSTATUS IoCreateDevice(
37 _In_ PDRIVER_OBJECT DriverObject,
38 _In_ ULONG DeviceExtensionSize,
39 _In_opt_ PUNICODE_STRING DeviceName,
40 _In_ DEVICE_TYPE DeviceType,
41 _In_ ULONG DeviceCharacteristics,
42 _In_ BOOLEAN Exclusive,
43 _Out_ PDEVICE_OBJECT *DeviceObject
44 );
45 */
46 Status = IoCreateDevice(pDriverObject,
47 0,
48 &usDevName,
49 FILE_DEVICE_UNKNOWN,
50 FILE_DEVICE_SECURE_OPEN,
51 TRUE,
52 &pDevObj);
53 if (!NT_SUCCESS(Status)) //检查返回值
54 {
55 return Status;
56 }
57
58 //DO_BUFFERED_IO or DO_DIRECT_IO
59 //Specifies the type of buffering that is used by the I/O manager for I/O requests that are sent to the device stack.
60 //Higher-level drivers OR this member with the same value as the next-lower driver in the stack, except possibly for highest-level drivers.
61 pDevObj->Flags |= DO_BUFFERED_IO;
62
63 RtlInitUnicodeString(&usSymName, L"\\??\\FirstDevice");
64
65 //The IoCreateSymbolicLink routine sets up a symbolic link between a device object name and a user-visible name for the device.
66 /*
67 NTSTATUS IoCreateSymbolicLink(
68 _In_ PUNICODE_STRING SymbolicLinkName,
69 _In_ PUNICODE_STRING DeviceName
70 );
71 */
72 Status = IoCreateSymbolicLink(&usSymName, &usDevName); //DDK API 创建符号链接
73 if (!NT_SUCCESS(Status))
74 {
75 IoDeleteDevice(pDevObj); //删除设备对象
76 return Status;
77 }
78
79 return STATUS_SUCCESS;
80 }
81
82 //打开设备的函数
83 NTSTATUS CreateCompleteRoutine(PDRIVER_OBJECT pDriverObject, PIRP pIrp)
84 {
85 NTSTATUS Status;
86
87 Status = STATUS_SUCCESS;
88
89 KdPrint(("Create"));
90
91 //A driver sets an IRP's I/O status block to indicate the final status of an I/O request, before calling IoCompleteRequest for the IRP.
92
93 //This is the completion status, either STATUS_SUCCESS if the requested operation was completed successfully or an informational, warning, or error STATUS_ XXX value.
94 //For more information, see Using NTSTATUS values.
95 pIrp->IoStatus.Status = Status;
96 //This is the completion status, either STATUS_SUCCESS if the requested operation was completed successfu