2009 01 09 12 07 [winddk] 如何寫 NT native application (1)

那什麼是 NT native application ?

如果你有仔細讀過關於 Windows NT 的資料,

你應該知道 Windows NT 有所謂的 Sub-System,

而 Sub-System 包涵了我們大家常用的 win32 sub-system,

還有偶而會看到的 POSIX ,

至於 OS/2 我就不知道在哪裡可以看到。

大家常用的 win32 sub-system ,只是 NT 底下的次系統。

(迷之音:好像什麼都沒解釋到~~~)

而 win32 sub-system 事實上是會 call 所謂的 NT native API 。

但是許多 NT native API 並沒有被公開,或者有詳細的文件。

 

大家應該都有看過在windows NT開機過程中,

有隻程式叫做 autochk.exe,

它會備份和還原系統設定到初始狀態,

當然也會掃描硬碟機是否正確運作。

它會執行在 windows NT 開機過程中的藍色畫面中,

只是一個簡單的 UI 介面。

而它就是一隻 NT native application 。

 

而 autochk.exe 是被放在 c:\windows\system32 下。

你可以試著去執行它,你會得到下面的訊息。

C:\>c:\WINDOWS\system32\autochk.exe
c:\WINDOWS\system32\autochk.exe 應用程式無法在 Win32 模式中執行。

這表示這個EXE檔並不是 win32 application。

如果你有 hiew 或者是 PE Explorer,

便可以看到 PE Header 裡的 Subsystem 是 1.

你可以參考以下各個數值所代表的意義。

    IMAGE_SUBSYSTEM_NATIVE (1)
The binary doesn't need a subsystem. This is used for drivers.

IMAGE_SUBSYSTEM_WINDOWS_GUI (2)
The image is a Win32 graphical binary. (It can still open a
console with AllocConsole() but won't get one automatically at
startup.)

IMAGE_SUBSYSTEM_WINDOWS_CUI (3)
The binary is a Win32 console binary. (It will get a console
per default at startup, or inherit the parent's console.)

IMAGE_SUBSYSTEM_OS2_CUI (5)
The binary is a OS/2 console binary. (OS/2 binaries will be in
OS/2 format, so this value will seldom be used in a PE file.)

IMAGE_SUBSYSTEM_POSIX_CUI (7)
The binary uses the POSIX console subsystem.

 

而 Autochk 被執行的時機,是在 Windows NT 開機 (boot) ,

載入系統開機驅動程式,以及啟用記憶體分頁機制。

在這時候, Session Manager (smss.exe) 剛進入 Windows NT user mode,

尚未執行任何應用程式。

這時它會去參考 registry 中的:

HKLM\System\CurrentControlSet\Control\Session Manager\BootExecute

通常你會看到 "autochk autochk *"。

而如果你要加入你自己的 native application ,

也是要加在這邊。

你可以使用下面的方式加進去。

reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager" /v BootExecute /t REG_MULTI_SZ /d "autochk autochk *\0nativeApplication args1 args2 args3\0" /f

對 reg 有興趣的話,你可以自己看 reg 的用法。

到這裡已經說明了 native application 的執行時機以及位置。

參考資料:

http://technet.microsoft.com/en-us/sysinternals/bb897447.aspx