Explorar el Código

以管理员身份可以正常编译

Gogs hace 3 semanas
padre
commit
100d7682c3

+ 6 - 1
common/CommKitIoctl.h

@@ -2,7 +2,11 @@
 // 被 dll/ 与 driver/ 共同包含,确保双方契约一致
 #pragma once
 
+// 内核模式:CTL_CODE 由 wdm.h/ntddk.h 提供
+// 用户模式:CTL_CODE 由 winioctl.h 提供
+#ifndef _NTDDK_
 #include <winioctl.h>
+#endif
 
 // ============================================================================
 // 用户态 CreateFile 使用的设备名(\\.\CommModifyKit)
@@ -48,6 +52,7 @@
 // ============================================================================
 // 单条事件结构(内核态 → 用户态)
 // 注意:字段对齐使用 1 字节 pack,便于跨位数(WOW64)传递
+// TimeStamp: 100ns 单位,从 1601-01-01 起算(与 FILETIME 相同)
 // ============================================================================
 #define COMMKIT_MAX_DATA          4096   // 单条事件最大数据字节数
 #define COMMKIT_EVENT_BATCH       16     // 单次 IOCTL 最多返回事件数
@@ -56,7 +61,7 @@
 #pragma pack(push, 1)
 typedef struct _COMMKIT_EVENT {
     INT32  Sequence;                     // 递增序列号(每次回调递增)
-    double TimeStamp;                    // OLE Automation date(0=用当前时间)
+    UINT64 TimeStamp;                    // 100ns 单位时间戳(0=用当前时间)
     UINT32 ComNumber;                    // 串口编号(COM n 的 n)
     UINT32 EventType;                    // 事件类型(见 CommKitEvents.h)
     UINT32 DataSize;                     // 有效数据字节数(<= COMMKIT_MAX_DATA)

+ 6 - 20
dll/CommModifyKit.vcxproj

@@ -18,7 +18,6 @@
       <Platform>x64</Platform>
     </ProjectConfiguration>
   </ItemGroup>
-
   <PropertyGroup Label="Globals">
     <VCProjectVersion>16.0</VCProjectVersion>
     <Keyword>Win32Proj</Keyword>
@@ -26,21 +25,19 @@
     <RootNamespace>CommModifyKit</RootNamespace>
     <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
   </PropertyGroup>
-
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-
   <!-- Debug|Win32 -->
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
     <ConfigurationType>DynamicLibrary</ConfigurationType>
     <UseDebugLibraries>true</UseDebugLibraries>
-    <PlatformToolset>v142</PlatformToolset>
+    <PlatformToolset>v145</PlatformToolset>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
   <!-- Release|Win32 -->
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
     <ConfigurationType>DynamicLibrary</ConfigurationType>
     <UseDebugLibraries>false</UseDebugLibraries>
-    <PlatformToolset>v142</PlatformToolset>
+    <PlatformToolset>v145</PlatformToolset>
     <WholeProgramOptimization>true</WholeProgramOptimization>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
@@ -48,27 +45,23 @@
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
     <ConfigurationType>DynamicLibrary</ConfigurationType>
     <UseDebugLibraries>true</UseDebugLibraries>
-    <PlatformToolset>v142</PlatformToolset>
+    <PlatformToolset>v145</PlatformToolset>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
   <!-- Release|x64 -->
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
     <ConfigurationType>DynamicLibrary</ConfigurationType>
     <UseDebugLibraries>false</UseDebugLibraries>
-    <PlatformToolset>v142</PlatformToolset>
+    <PlatformToolset>v145</PlatformToolset>
     <WholeProgramOptimization>true</WholeProgramOptimization>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
-
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
   <ImportGroup Label="ExtensionSettings" />
   <ImportGroup Label="Shared" />
   <ImportGroup Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"
-            Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')"
-            Label="LocalAppDataPlatform" />
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
   </ImportGroup>
-
   <!-- 通用属性 -->
   <!-- 项目名 CommModifyKit,输出文件名 CommModifyKit.dll(统一命名) -->
   <PropertyGroup>
@@ -76,7 +69,6 @@
     <IntDir>$(SolutionDir)build\obj\CommModifyKit\$(Configuration)\$(Platform)\</IntDir>
     <TargetName>CommModifyKit</TargetName>
   </PropertyGroup>
-
   <!-- 通用编译选项 -->
   <ItemDefinitionGroup>
     <ClCompile>
@@ -99,7 +91,6 @@
       <ModuleDefinitionFile>CommModifyKit.def</ModuleDefinitionFile>
     </Link>
   </ItemDefinitionGroup>
-
   <!-- Debug 特定 -->
   <ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
     <ClCompile>
@@ -107,7 +98,6 @@
       <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
     </ClCompile>
   </ItemDefinitionGroup>
-
   <!-- Release 特定 -->
   <ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
     <ClCompile>
@@ -121,7 +111,6 @@
       <OptimizeReferences>true</OptimizeReferences>
     </Link>
   </ItemDefinitionGroup>
-
   <!-- 源文件 -->
   <ItemGroup>
     <ClCompile Include="pch.cpp">
@@ -135,7 +124,6 @@
     <ClCompile Include="EventLoop.cpp" />
     <ClCompile Include="MonitorManager.cpp" />
   </ItemGroup>
-
   <!-- 头文件 -->
   <ItemGroup>
     <ClInclude Include="pch.h" />
@@ -147,12 +135,10 @@
     <ClInclude Include="..\common\CommKitIoctl.h" />
     <ClInclude Include="..\common\CommKitEvents.h" />
   </ItemGroup>
-
   <!-- 模块定义文件 -->
   <ItemGroup>
     <None Include="CommModifyKit.def" />
   </ItemGroup>
-
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets" />
-</Project>
+</Project>

+ 3 - 3
dll/EventLoop.cpp

@@ -91,9 +91,9 @@ void EventLoop::Run() {
             const COMMKIT_EVENT& e = batch[i];
             if (callback_) {
                 // 调用用户注册的回调
-                // 数据指针:const_cast 转换以匹配 TOnData 签名
-                // 注意:回调应只读 lpData,不应释放
-                callback_(e.Sequence, e.TimeStamp, e.ComNumber,
+                // TimeStamp 是 100ns 单位,转换为 double(用户可根据需要自行处理)
+                double timestamp = static_cast<double>(e.TimeStamp);
+                callback_(e.Sequence, timestamp, e.ComNumber,
                           e.EventType, e.DataSize,
                           const_cast<char*>(e.Data));
             }

+ 13 - 21
driver/ClientConnection.cpp

@@ -8,27 +8,17 @@
 
 namespace commkit_driver {
 
-ClientConnection::ClientConnection()
-    : ports_count_(0), control_device_(nullptr), callback_registered_(FALSE) {
+// 全局实例
+ClientConnection g_ClientConnection;
+
+void ClientConnection::Initialize() {
+    ports_count_ = 0;
+    control_device_ = nullptr;
+    callback_registered_ = FALSE;
     KeInitializeSpinLock(&ports_lock_);
     RtlZeroMemory(ports_table_, sizeof(ports_table_));
 }
 
-ClientConnection::~ClientConnection() {
-    Cleanup();
-}
-
-ClientConnection& GetClientConnection() {
-    static ClientConnection instance;
-    return instance;
-}
-
-NTSTATUS ClientConnection::Initialize(WDFDRIVER driver) {
-    UNREFERENCED_PARAMETER(driver);
-    // 控制设备创建详见 QueueCallback.cpp / DriverEntry.cpp
-    return STATUS_SUCCESS;
-}
-
 void ClientConnection::Cleanup() {
     // 释放所有端口的环形缓冲
     KIRQL old_irql;
@@ -133,7 +123,8 @@ NTSTATUS ClientConnection::HandleAttachPort(ULONG com_number) {
     EventRingBuffer* ring = (EventRingBuffer*)ctx->RingBuffer;
     static LONG seq = 0;
     LONG cur = InterlockedIncrement(&seq);
-    ring->Push((ULONG)cur, 0.0, com_number, COMMKIT_OP_OPEN, 0, nullptr);
+    UINT64 timestamp = KeQueryInterruptTime();  // 100ns 单位
+    ring->Push((ULONG)cur, timestamp, com_number, COMMKIT_OP_OPEN, 0, nullptr);
 
     ctx->MonitoringEnabled = TRUE;
     return STATUS_SUCCESS;
@@ -150,9 +141,10 @@ NTSTATUS ClientConnection::HandleDetachPort(ULONG com_number) {
     // 推入 OP_CLOSE 事件
     if (ctx->RingBuffer) {
         EventRingBuffer* ring = (EventRingBuffer*)ctx->RingBuffer;
-        static LONG seq = 0;
-        LONG cur = InterlockedIncrement(&seq);
-        ring->Push((ULONG)cur, 0.0, com_number, COMMKIT_OP_CLOSE, 0, nullptr);
+        static LONG seq2 = 0;
+        LONG cur = InterlockedIncrement(&seq2);
+        UINT64 timestamp = KeQueryInterruptTime();
+        ring->Push((ULONG)cur, timestamp, com_number, COMMKIT_OP_CLOSE, 0, nullptr);
     }
     return STATUS_SUCCESS;
 }

+ 10 - 8
driver/ClientConnection.h

@@ -13,13 +13,10 @@ namespace commkit_driver {
 
 class ClientConnection {
 public:
-    ClientConnection();
-    ~ClientConnection();
+    // 初始化(构造不分配资源)
+    void Initialize();
 
-    // 初始化:创建控制设备 + 符号链接
-    NTSTATUS Initialize(WDFDRIVER driver);
-
-    // 反初始化
+    // 清理资源(驱动卸载时调用)
     void Cleanup();
 
     // ====== IOCTL 处理接口(由 QueueCallback 调用)======
@@ -76,7 +73,12 @@ private:
     BOOLEAN             callback_registered_;
 };
 
-// 全局单例
-ClientConnection& GetClientConnection();
+// 全局实例(手动管理生命周期)
+extern ClientConnection g_ClientConnection;
+
+// 访问全局实例
+inline ClientConnection& GetClientConnection() {
+    return g_ClientConnection;
+}
 
 } // namespace commkit_driver

+ 12 - 3
driver/CommModifyKitDriver.vcxproj

@@ -15,7 +15,7 @@
     <ProjectGuid>{A1B2C3D4-0001-0001-0001-000000000002}</ProjectGuid>
     <TemplateGuid>{497e31cb-8862-4f4f-b67a-2b3e74da00a7}</TemplateGuid>
     <RootNamespace>CommModifyKit</RootNamespace>
-    <WindowsTargetPlatformVersion>$(WindowsTargetPlatformVersion_10)</WindowsTargetPlatformVersion>
+    <WindowsTargetPlatformVersion>10.0.28000.0</WindowsTargetPlatformVersion>
     <Configuration>Debug</Configuration>
     <Platform Condition="'$(Platform)' == ''">x64</Platform>
     <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
@@ -44,17 +44,22 @@
   </ImportGroup>
 
   <PropertyGroup>
+    <!-- 统一输出目录:.sys, .inf, .cat 都在同一位置 -->
     <OutDir>$(SolutionDir)build\$(Configuration)\$(Platform)\</OutDir>
-    <IntDir>$(SolutionDir)build\obj\CommModifyKitDriver\$(Configuration)\$(Platform)\</IntDir>
+    <IntDir>$(SolutionDir)build\$(Configuration)\$(Platform)\</IntDir>
     <!-- TargetName=CommModifyKit,输出 CommModifyKit.sys
          与 INF/服务名一致 -->
     <TargetName>CommModifyKit</TargetName>
+    <!-- 驱动打包目录 -->
+    <PackageDir>$(SolutionDir)build\$(Configuration)\$(Platform)\</PackageDir>
+    <!-- 开发阶段禁用 Inf2Cat 验证(仅测试,发布前需重新启用) -->
+    <EnableInf2cat>false</EnableInf2cat>
   </PropertyGroup>
 
   <ItemDefinitionGroup>
     <ClCompile>
       <AdditionalIncludeDirectories>..\common;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_KERNEL_MODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <WarningLevel>Level3</WarningLevel>
       <DisableSpecificWarnings>4100;4201;4204;4221</DisableSpecificWarnings>
       <AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
@@ -65,7 +70,11 @@
     <Inf>
       <SpecifyArchitecture>true</SpecifyArchitecture>
       <Architecture>x64</Architecture>
+      <TimeStamp>1.0.0.0</TimeStamp>
     </Inf>
+    <DriverSign>
+      <FileDigestAlgorithm>SHA256</FileDigestAlgorithm>
+    </DriverSign>
   </ItemDefinitionGroup>
 
   <ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">

+ 3 - 0
driver/DriverEntry.cpp

@@ -30,6 +30,9 @@ extern "C" NTSTATUS DriverEntry(PDRIVER_OBJECT driver_object,
     NTSTATUS status;
     WDF_DRIVER_CONFIG cfg;
 
+    // 初始化全局客户端连接管理器
+    commkit_driver::GetClientConnection().Initialize();
+
     // 初始化 WDF 配置
     WDF_DRIVER_CONFIG_INIT(&cfg, EvtDeviceAdd);
     cfg.EvtDriverUnload = EvtDriverUnload;

+ 5 - 10
driver/EventRingBuffer.cpp

@@ -5,17 +5,12 @@
 
 namespace commkit_driver {
 
-EventRingBuffer::EventRingBuffer()
-    : buffer_(nullptr), head_(0), tail_(0), count_(0) {
-    KeInitializeSpinLock(&lock_);
-}
-
-EventRingBuffer::~EventRingBuffer() {
-    Cleanup();
-}
-
 NTSTATUS EventRingBuffer::Initialize() {
     // 分配非分页内存(可在 DISPATCH_LEVEL 访问)
+    buffer_ = nullptr;
+    head_ = tail_ = count_ = 0;
+    KeInitializeSpinLock(&lock_);
+
     ULONG size = sizeof(COMMKIT_EVENT) * COMMKIT_RING_CAPACITY;
     buffer_ = (COMMKIT_EVENT*)ExAllocatePool2(
         POOL_FLAG_NON_PAGED, size, 'BCMK');
@@ -35,7 +30,7 @@ void EventRingBuffer::Cleanup() {
     count_ = head_ = tail_ = 0;
 }
 
-void EventRingBuffer::Push(ULONG sequence, DOUBLE timestamp,
+void EventRingBuffer::Push(ULONG sequence, UINT64 timestamp,
                             ULONG com_number, ULONG event_type,
                             ULONG data_size, PVOID data) {
     KIRQL old_irql;

+ 2 - 4
driver/EventRingBuffer.h

@@ -13,9 +13,6 @@ namespace commkit_driver {
 
 class EventRingBuffer {
 public:
-    EventRingBuffer();
-    ~EventRingBuffer();
-
     // 初始化环形缓冲(分配内存)
     NTSTATUS Initialize();
 
@@ -23,8 +20,9 @@ public:
     void Cleanup();
 
     // 推入一条事件(拷贝 lpData 前 data_size 字节)
+    // timestamp: 100ns 单位时间戳(使用 KeQueryInterruptTime 获取)
     // 调用者 IRQL <= DISPATCH_LEVEL
-    void Push(ULONG sequence, DOUBLE timestamp,
+    void Push(ULONG sequence, UINT64 timestamp,
               ULONG com_number, ULONG event_type,
               ULONG data_size, PVOID data);
 

+ 7 - 1
driver/QueueCallback.cpp

@@ -1,6 +1,8 @@
 // QueueCallback.cpp - I/O Queue 回调实现
 #include <ntddk.h>
 #include <wdf.h>
+#include <initguid.h>
+#include <wdmsec.h>
 #include "QueueCallback.h"
 #include "ClientConnection.h"
 #include "DeviceContext.h"
@@ -8,10 +10,14 @@
 
 namespace commkit_driver {
 
+// SDDL: System and Administrators have full access
+static const UNICODE_STRING SddlSysAdminFullAccess = 
+    RTL_CONSTANT_STRING(L"D:P(A;;GA;;;SY)(A;;GA;;;BA)");
+
 NTSTATUS CreateControlDevice(WDFDRIVER driver) {
     NTSTATUS status;
     PWDFDEVICE_INIT init = WdfControlDeviceInitAllocate(
-        driver, &SDDL_DEVOBJ_SYS_ONLY_ADM);
+        driver, (PCUNICODE_STRING)&SddlSysAdminFullAccess);
     if (!init) {
         return STATUS_INSUFFICIENT_RESOURCES;
     }

+ 6 - 4
driver/SerialFilter.cpp

@@ -13,9 +13,9 @@ namespace commkit_driver {
 // 全局原子序列号(每个事件递增)
 static LONG g_sequence_counter = 0;
 
-// 获取当前 OLE Automation 日期(简化实现:返回 0,由 DLL 转换为当前时间
-static DOUBLE GetCurrentTimeStamp() {
-    return 0.0;
+// 获取当前时间戳(100ns 单位
+static UINT64 GetCurrentTimeStamp() {
+    return KeQueryInterruptTime();
 }
 
 NTSTATUS SerialFilter::CreateAndAttach(WDFDRIVER driver,
@@ -130,7 +130,9 @@ NTSTATUS SerialFilter::DispatchWrite(PDEVICE_OBJECT dev, PIRP irp) {
 NTSTATUS SerialFilter::DispatchDeviceControl(PDEVICE_OBJECT dev, PIRP irp) {
     PDEVICE_CONTEXT ctx = (PDEVICE_CONTEXT)dev->DeviceExtension;
     if (!ctx) {
-        IoCompleteRequest(irp, STATUS_INVALID_DEVICE_REQUEST);
+        irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
+        irp->IoStatus.Information = 0;
+        IoCompleteRequest(irp, IO_NO_INCREMENT);
         return STATUS_INVALID_DEVICE_REQUEST;
     }
     // 透传 DeviceControl 给下层