DLLs in Kernel Mode

32位ControlCan.dll 供实现周立功can设备报文收发调用 将ControlCan.dll和kerneldlls文件夹放置在.py文件的同级目录下,通过python的ctypes模块调用ControlCan.dll接口函数实现can报文的收发操作。 立即下载

Win32 user-mode programmers are accustomed to using and creating dynamic link libraries, or DLLs, to compartmentalize their applications and enable efficient code reuse. The typical application includes many DLLs, and careful design allows those DLLs to be reused many times over.

Kernel driver writers are often not aware that they can use exactly the same concept in kernel mode. The standard DDK even includes several samples (for example, storage/changers/class). In this article, I will show you a working (though trivial) example of a kernel DLL.

 

The Basics

In terms of the C source code, a kernel DLL is virtually identical to a user-mode DLL. The primary difference is that you may not call any user-mode APIs from a kernel DLL. That should not be surprising.

You use a kernel DLL just like a user-mode DLL: the linker builds an import library when it builds your DLL, and you include that library in the target library list for any driver that needs to use the DLL. No registry magic is required, and no special action is needed to start or stop the DLL. Your kernel DLL will be automatically loaded as soon as any other driver makes a reference to it, and is automatically unloaded when the last referring driver unloads.1

You can export DLL entry points from a normal WDM driver as well. There are many drivers in the operating system that export entry points for other drivers to use. For example, the ubiquitous NTOSKRNL.EXE, which contains all of the Ex, Fs, Io, Ke, Mm, Nt, and Zw entry points used by virtually every driver, is nothing more than a standard kernel driver with exports, exactly like the DLL we will describe here.

 

Digging In

OK, now let's get in to a few of the details. All of the source files for this project are available at http://www.wd-3.com/downloads/kdll.zip.

The most important step to take when creating an export driver is to specify the TARGETTYPE macro in the "sources" file:

TARGETTYPE=EXPORT_DRIVER

This type tells the build system that our project will build a kernel-mode driver that is exporting functions. If you leave TARGETTYPE set to DRIVER, as with a normal kernel-mode driver, your exports will not be available to other drivers.

Your DLL must include the standard DriverEntry entry point, but the system won't actually call that entry point. This requirement is an artifact of the build system, which adds /ENTRY:DriverEntry to the linker options for every kernel driver. An EXPORT_DRIVER can also function as a normal driver, and the build system cannot tell whether we want to do that or not, so we have to supply this dummy entry point for an export-only DLL.

If you do need to take special one-time action on loading and unloading, you should export two special enty points called DllInitialize and DllUnload:

NTSTATUS DllInitialize(IN PUNICODE_STRING RegistryPath)
  {
  DbgPrint("SAMPLE: DllInitialize(%wZ)/n", RegistryPath);
  return STATUS_SUCCESS;
  }

NTSTATUS DllUnload()
  {
  DbgPrint("SAMPLE: DllUnload/n");
  return STATUS_SUCCESS;
  }

The RegistryPath string passed to DllInitialize is of the form:

/Registry/Machine/System/CurrentControlSet/Services/SAMPLE

You would only include a DllInitialize routine in an export-only DLL -- that is, in a driver that's used exclusively as a DLL and not as a real driver for hardware. You do not need to define a service key for such a driver. Consequently, the RegistryPath string is not probably not going to be useful to you, because it likely names a registry key that doesn't even exist.

Compatibility caution: A bug in Windows 98 Gold will prevent your DLL from loading if you include a DllInitialize entry point. Further, Windows 98 Second Edition and Windows Millennium will never call the DllUnload entry point. A kernel DLL in these systems, once loaded, is permanent.

 

Declaring Exports

Beyond those two special entry points, you can create whatever entry point names you find convenient. You just need to identify those entry point names to the linker. There are two ways to do that. For our sample purposes, I will be exporting one functional entry point from our DLL:

NTSTATUS SampleDouble(int* pValue)
  {
  DbgPrint("SampleDouble: %d/n", *pValue);
  *pValue *= 2;
  return STATUS_SUCCESS;
  }

There are two ways to tell the linker that you want to export a function. The first method is to enumerate the names in a .DEF file. The .DEF file is familiar to anyone who has done Win16 or Win32 programming. It is a special file used to give instructions to the linker that cannot be easily included on the command line. In this case, it enumerates the names of the routines we want to export from the DLL. The linker uses this list to create the symbol tables in the DLL, and to create an import library that we can use in other projects to call into our DLL. Our .DEF file looks like this:

NAME SAMPLE.SYS

EXPORTS
  DllInitialize PRIVATE
  DllUnload PRIVATE
  SampleDouble

DllInitialize and DllUnload must both be marked as PRIVATE. This tells the linker to export the symbol from the DLL executable file, but not to include it in the import library it builds. The build system will flag an error if these are not marked PRIVATE.

The import library is the fundamental mechanism used to map a function's name to the DLL that contains that function. Almost all of the libraries you use in Win32 program are import libraries, including kernel libraries such as ntdll.lib and ntoskrnl.lib, and user-mode libraries such as kernel32.lib, user32.lib, and gdi32.lib. Such libraries do not actually contain any code. Instead, they contain a set of linker tables that contains information that means something like, "The name MySampleFunction maps to _MySampleFunction@4 in MY.DLL".

The linker embeds this information into the executable file, so that the operating system can tie all of the loose ends together when the EXE or DLL is finally loaded into memory.

We have to use the special DLLDEF macro in the "sources" file to identify the name of our .DEF file:

DLLDEF=sample.def

The second way to identify your exported entry points is to use a declspec attribute in your source code:

__declspec(dllexport) NTSTATUS SampleDouble(int* pValue)
  {
  ...
  }

This has the same effect as listing the name in the .DEF file. In general, I am in favor of reducing the number of files in my project, since that automatically reduces the number of chances for error. However, in this case, there is a catch: DllInitialize and DllUnload must be marked as PRIVATE exports, and to my knowledge, there is no way to mark an export PRIVATE without using a .DEF file. Thus, you will HAVE to use the .DEF file at least for those two names. Whether you include your other exports in the .DEF file or mark them with __declspec(dllexport) is completely up to you.

The sample source code for this article is in C. If you wish to export functions from a DLL written in C++, you have an additional complication to consider. Because C++ allows multiple functions with the same name but different argument lists, C++ compilers "decorate" their symbol names with extra characters that specifically identify the return type and argument list. For example, the actual name of the SampleDouble function when compiled in a C++ module is ?SampleDouble@@YGJPAH@Z. If you try to call this function from another C++ driver, it would work, but if you try to call it from a C driver, the external names won't line up.

The way to fix this is to use a special language modifier on the extern declaration, like this:

extern "C" NTSTATUS SampleDouble(int* pValue)
  {
  ...
  }

With that information, we can now bring up a DDK command shell and do a build. For this example, we build a file called sample.sys. We copy this file to the traditional location for drivers, %WINDIR%/SYSTEM32/DRIVERS, and we are ready to use our DLL. We can verify the exports using the "dumpbin" command, just like you would with a user-mode DLL:

C:/Dev/KernDLL>dumpbin /exports objfre_w2k_x86/i386/sample.sys

Microsoft (R) COFF/PE Dumper Version 7.00.9210
Copyright (C) Microsoft Corporation.  All rights reserved.

Dump of file objfre_w2k_x86/i386/sample.sys

File Type: EXECUTABLE IMAGE

  Section contains the following exports for SAMPLE.SYS

  00000000 characteristics
  3EEEB656 time date stamp Mon Jun 16 23:33:58 2003
  0.00 version
    1 ordinal base
    3 number of functions
    3 number of names
        
  ordinal hint RVA      name
        
    1    0 0000031B DllInitialize
    2    1 00000347 DllUnload
    3    2 00000368 SampleDouble
    ...

Alternatively, you can use the Dependency Walker applet (DEPENDS.EXE) from the Platform SDK to view the file:

Notice that the Subsystem displayed for all the modules in the bottom pane is "Native". If you ever see a "Win32" subsystem when you're looking at the dependencies for a driver or kernel DLL you've created, it means that you've called a user-mode API function.

Calling Into the DLL

To make it convenient to call the entry points in our DLL, we probably want to create a header file to include in our calling driver. For this sample, we can use this simple sample.h:

#pragma once
EXTERN_C DECLSPEC_IMPORT NTSTATUS SampleDouble(int* pValue);

We use several custom macros here to make the file flexible and easier to read. These macros are defined in <ntdef.h>, which is included automatically in most drivers via <wdm.h>

EXTERN_C expands to extern "C" in a C++ source file, and to plain old extern in a C source file. This ensures that no unwanted decoration will occur in the calling program.

DECLSPEC_IMPORT expands to the Visual C++ specifier __declspec(dllimport). This is the complement of the __declspec(dllexport) macro we used above, and tells the compiler that the call will be satisfied from a DLL at run-time, rather than being loaded at link-time. This allows the compiler and the linker to optimize the runtime linkage to SampleDouble.2

When you define a header file like this that contains function prototypes for a DLL, it's a good idea to include that header in the DLL project too. Doing that gives you a compile-time check that you've correctly prototyped the functions. All those DECLSPEC_IMPORT directives will cause warning messages from the compiler, however. You can cure that minor problem by putting some conditional compilation into the header:

#pragma once
#ifdef SAMPLE_INTERNAL
  #define SAMPLE_IMPORT
#else
  #define SAMPLE_IMPORT DECLSPEC_IMPORT
#endif

EXTERN_C SAMPLE_IMPORT SampleDouble(int* pValue);

You define the symbol SAMPLE_INTERNAL in your DLL project, which causes the header to not have any __declspec directives. Other projects that include the header don't define this symbol, which means that the header does contain the directives.

Testing

To test our sample, I added the following code to the DriverEntry of a kernel driver I have been working on:

#include "sample.h"

NTSTATUS DriverEntry(...)
  {
  PDEVICE_OBJECT deviceObject = NULL;
  NTSTATUS       ntStatus;
  WCHAR          deviceNameBuffer[] = L"//Device//dbgdrvr";
  UNICODE_STRING deviceNameUnicodeString;
  WCHAR          deviceLinkBuffer[] = L"//DosDevices//DBGDRVR";
  UNICODE_STRING deviceLinkUnicodeString;
  int xxx = 19;
 
  KdPrint(("HELPER.SYS: entering DriverEntry/n"));
  KdPrint (("Helper: before is %d/n", xxx));
  SampleDouble(&xxx);
  KdPrint(("Helper:  after is %d/n", xxx));
  ...
  }

I copied "sample.lib" from my sample build directory into the test build directory, and added "sample.lib" to the TARGETLIBS macro in "sources". In fact, because my test driver is so simple, the entire sources file is here:

TARGETNAME=dbgdrvr
TARGETPATH=obj
TARGETTYPE=DRIVER

TARGETLIBS=sample.lib

SOURCES=dbgdrvr.c

I then built my driver and copied the binary to SYSTEM32/DRIVERS. This is an old-style NT 4 driver, so I started it up with "net start" and stopped it with "net stop". The resulting debug log looked like this:

SAMPLE: DllInitialize(/REGISTRY/MACHINE/SYSTEM/CURRENTCONTROLSET/SERVICES/SAMPLE)
HELPER.SYS: entering DriverEntry
Helper: before is 19
SampleDouble: 19
Helper:  after is 38
HELPER.SYS: unloading
SAMPLE: DllUnload

Note that our DLL loads before the calling driver starts to execute, and unloads after the calling driver shuts down. This, again, is similar to the way a Win32 user-mode DLL operates: the system does not know whether we intend to call the DLL within our DriverEntry or not, so it ensures that all DLLs are in place an initialized before launching the referring driver.

You can see the registry path being passed to the DllInitialize entry point of my kernel DLL. You'll have to trust me when I tell you there is no such path in my registry; the string is just for decoration.

 

Conclusion

This is a lot of work just to double an integer, but it demonstrates a powerful and little-known concept. With a little forethought, you can build a centralized repository for all of your interesting overhead routines, hiding the sometimes daunting complexity of the kernel APIs in a simple wrapper that you can use over and over again.

 

 

Tim Roberts is a hopeless software engineer who programs both for fun and for profit. Tim has been programming computers for more than a third of a century, on everything from microcontrollers to mainframes.

Tim is a partner in Providenza & Boekelheide, Inc., a technology consulting company in the Silicon Forest just outside of Portland, Oregon. P&B provides all kinds of hardware and software consulting, specializing in graphics, video, and multimedia.


1 -- Kernel DLLS are never unloaded in Windows 98 Second Edition or in Windows Millennium, though. I'll say more about platform compatibility later on in the article.

2 -- If you give the compiler the clue that a given function will be imported from another DLL, it generates an indirect call through the module's indirect address table. If you don't give the compiler this clue, it generates a call to an external function. The linker then includes a function thunk (taken from the import library) that contains an indirect call through the indirect address table. Thus, using __declspec(dllimport) eliminates the thunk in the middle and saves a few machine cycles at run time.

 

CAN通讯labvIEW例程 CAN通讯 labvIEW例程 源代码,可以交流学习。 立即下载

相关推荐

python_DLLs

python 3.1 /python/DLLs/

(转载)DLLs in Kernel Mode

DLLs in Kernel ModeJuly 15, 2003Tim RobertsCopyright © 2003, Tim Roberts. All rights reservedWin32 user-mode programmers are accustomed to using and creating dynamic link libraries, or DLLs, to co

无限天空 1653

基于gdal用c#读取hdf4文件的方法及相关DLL

基于gdal用c#读取hdf4文件的方法及相关DLL

探索神秘代码:Udis86 —— 强大的x86/x86-64反汇编器

探索神秘代码:Udis86 —— 强大的x86/x86-64反汇编器 项目地址:https://gitcode.com/gh_mirrors/ud/udis86 项目介绍 在软件开发和逆向工程的世界中,理解二进制代码的内在工作原理是至关重要的。Udis86是一个专为x86和x86-64架构设计的高性能反汇编库,它允许开发者将原始二进制数据流转换成可读性强的汇编指令。这个开源项目不仅提供了一个简洁的...

gitblog_00021的博客 626

RTAB-Map实战:用RGB-D相机5步搞定机器人自主建图(附避坑指南)

本文提供了一份详细的RTAB-Map实战指南,通过5个核心步骤,指导用户使用RGB-D相机(如Intel RealSense D435i)快速实现机器人自主建图。内容涵盖环境准备、传感器启动、核心参数配置、实战调优及地图后处理,并重点解析了算法关键参数与常见避坑方案,旨在帮助初学者高效搭建鲁棒的视觉SLAM系统。

g9h0i1的博客 794

CANoe的安装教程

CANoe的安装教程

weixin_59090531的博客 1万+

内核模式的dll编写与调用

http://www.microsoft.com/whdc/driver/tips/KmDLL.mspxhttp://www.wd-3.com/archive/KernelDlls.htm 

1316

智能车赛道识别:八邻域算法的实战解析与优化

本文深入解析了智能车赛道识别中八邻域算法的核心原理与实战优化。作为兼顾性能与稳定性的经典方案,该算法通过模拟探险家环顾八方的策略,能精准追踪弯道与直道边界。文章详细拆解了代码逻辑,并提供了边界平滑、异常处理及应对十字路口、环岛等复杂场景的关键优化策略,助力开发者提升智能车视觉系统的鲁棒性与实时性。

weixin_29228781的博客 267

使用了动态库的程序运行说明以CAN通信编程为例

使用了动态库的程序运行说明以CAN通信编程为例

QQ3200028121的博客 763

西门子CPU与汇川伺服通信与控制

第三方驱动器的配置内容和西门子的配置内容基本一致,基本上会一种即可知道其他品牌的配置默认报文,需要激活硬限位才能收到限位信号默认报文,原点信号不能实时输出到PLC;自定义报文,需要伺服端设置DIN点位。

大小曲奇的博客 1万+

告别官方WebRTC的30G编译:我用libdatachannel给USB摄像头做了个轻量级网页监控

本文介绍了一种基于libdatachannel的轻量级WebRTC监控方案,通过USB摄像头实现实时视频推流。相比官方WebRTC库30GB的庞大编译体积,libdatachannel仅需几十MB,大幅简化了开发流程。文章详细讲解了从视频采集、FFmpeg编码到WebRTC传输的全过程,并提供了性能优化和部署方案,帮助开发者快速构建高效的网页监控系统。

weixin_29207533的博客 537

python调用32位的ControlCan.dll实现can报文的收发

python重新封装调用ControlCan.dll内部函数实现can报文的收发。

Logintern09的博客 3363

DolphinScheduler租户配置踩坑实录:手把手教你修复‘tenant not exists‘报错

本文深度解析DolphinScheduler的租户模型,并提供一套从界面到数据库的系统性排查流程,手把手教你修复常见的'tenant not exists'报错。文章揭示了该错误的本质是用户与租户数据关联不一致,并给出了通过UI或SQL更新的具体修复方案,同时分享了根因分析与预防措施,帮助用户从根本上理解和避免此类问题。

2w3e4r5t6y的博客 544

转载于MICROTIGER: Loading DLLs in Kernel Mode or User Mode

Loading DLLs in Kernel Mode or User Mode: Windows CE 5.0 vs. Windows Embedded CE 6.0One DLL cannot simultaneously load into both kernel mode and user mode. When you run an EXE or DLL, the code mus

kevin_83的专栏 1437

ISP Tuning实战指南:从基础到高级的色彩与亮度优化

本文详细介绍了ISP Tuning的基础概念与高级调优技术,包括黑电平校正(BLC)、自动白平衡(AWB)、色彩校正矩阵(CCM)和Gamma曲线调整等核心算法。通过实战案例和调试技巧,帮助工程师提升摄像头成像质量,解决高光过曝、暗部噪点等常见问题,适用于智能门铃、车载摄像头等多种场景。

weixin_30879169的博客 112

LangChain4j + MCP:从工具协议到生产级 Agent

这两年,很多团队都已经把「大模型问答」接入到系统里了:前端一个输入框,后端调一下 OpenAI / DeepSeek / 本地模型,返回一段回答——这类 「简单问答型」AI 功能它只能说,不会做:不会主动查数据库,不会调用你的接口,不会帮你真正执行脚本;面对复杂一点的需求,比如「帮我生成这个报表的 SQL 并执行一下」,普通 ChatGPT 式的问答就开始力不从心了。而Agent 智能体想解决的,就是这件事:不只是回答你「怎么做」,而是能自己思考、自己决定要不要用工具、再用工具把事做完。

OFFTime_we的博客 1157

Windows内核态DLL实例(DLLs in Kernel Mode)

最近根据要求写了一个内核态的dll算法,主要是为了对磁盘上数据块级别的裸数据进行压缩解压。 开发环境是:VMware中的Windows XP,开发工具是:ddk 2000和VC6.0 主要的参考书籍是:《Windows驱动开发技术详解》,里面详细的介绍各种驱动开发环境,Windows内核函数,及调试的工具DriverMonitor和Dbgview。   开发完成后,整理出3个文件夹: 1

213

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

利用AppInit_Dlls注入在win10上的限制

0x00 AppInit_Dlls注入方法特别简便,日常注入测试首选,在win7上屡试不爽,具体原理如下: support.microsoft.com/en-us/help/… docs.microsoft.com/en-us/windo…windows-7-and-windows-server-2008-r2 但是最近使用win10系统之后发现,注入方法失效。在检查过所有的配置都正确之后,决定使...

weixin_43787608的博客 3760

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Tracing NT Kernel-Mode Calls

Tracing NT Kernel-Mode Calls April 01, 2000 URL:http://www.drdobbs.com/tracing-nt-kernel-mode-calls/184416246 Tracing tools can solve problems that normal interactive debuggers are not wel...

weixin_30445169的博客 530

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

KD extension DLLs & KDCOM protocol

KD extension DLLs & KDCOM protocol<br />WinDbg debugger allows you to debug all modern versions of Windows using a built-in kernel debugger and either COM or IEEE1394 port. Let's see how is it implemented. To start windows in Kernel Debugging mode, you

Tommy(凌飞)的专栏 1443

Kernel Streaming(KS) tutorial

Kernel Streaming[This is preliminary documentation and subject to change.]Kernel streaming (KS) refers to the Microsoft-provided services that support kernel-mode processing of streamed data. Micr

chinaplus的专栏 2424

Windows 2000 Kernel Source Code Analysis-Part I

http://blog.chinaunix.net/uid-20517852-id-1936379.html Windows 2000 Kernel Source Code Analysis-Part I 这是我的关于Windows 2000内核细节系列文章中的第一篇。我会涉及到已泄漏的Windows 2000内核源代码。显然,我不会在文章中直接写出相关的内核代码,但我会清楚地

hfutljx的博客 1328

Win2K Kernel Hidden Process/Module Checker 0.1 (Proof-Of-Concept)

by Tan Chew Keong23 May 2004Updated : 27 May 2005 (Added Version 0.2beta2)Download Version 0.2-beta2 Traverses HandleTableListDownload Version 0.2-beta1 supports WinXPDownload Version 0.1 Note: Th

1989

基于Windows8与Visual Studio11开发第一个内核驱动程序

Windows 驱动程序的发展演变 我们在学习开发驱动程序时有必要弄清楚Windows设备驱动程序的发展演变过程(为了简便起见,以下简称驱动程序),以便明白我们将要开发什么样的驱动程序。这就象你开发一个应用程序时必须弄清楚它是运行在WINDOWS平台下还是在DOS平台下,否则我们能写出什么样的应用程序就可想而知了。       驱动程序开发者的各项任务之中,有许多是为特定的硬件编写驱动程序。由于W

尹成的技术博客 7259
上一篇: 书写NDIS过滤钩子驱动实现ip包过滤
下一篇: Places that viruses and trojans hide on start up
iiprogram
博客等级 码龄25年 1068粉丝 1515原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址