Windows XP 에서의장치관리자 : Device Driver 에관하여 May 29, 2015. CHONBUK NATIONAL UNIVERSITY Prof. Woonchul Ham 2015-05-28 1
개요 1. 장치관리자란? 2. Device Driver 작업환경은? 3. Driver 의구조 4. Plug & Play 5. Device Driver 응용사례 : UsbBulk.sys 6. Application Program 2015-05-28 2
장치관리자란? 내컴퓨터 -> 속성 -> 하드웨어 -> 장치관리자 2015-05-28 3
장치관리자란? (USB) 이곳을클릭 2015-05-28 4
장치관리자란? (USB) 2015-05-28 5
장치관리자란? (USB) 2015-05-28 6
장치관리자란? (USB) USBSTOR.SYS 파일을이해하고만들어본다. 이러한 *.SYS 파일이바로 Device Driver 이며, 이동적라이브러리를통하여응용프로그램 (*.exe) 이 OS 와의대화를통하여하드웨어를접근할수있게되는것이다. 2015-05-28 7
장치드라이버란? (USB) Applications User Mode Win32 API Kernel Mode Other Kernel Mode Driver Operating System Kernel File System Drivers Hardware Abstraction layer(hal) Hardware 2015-05-28 8
1. 장치관리자란? 2. Device Driver 작업환경은? 3. Driver 의구조 4. Plug & Play 5. Device Driver 응용사례 : UsbBulk.sys 6. Application Program 2015-05-28 9
2. Device Driver 작업환경은? 1. Windbg 설치 2. Windows Device Driver Tool kit 설치 3. NULL Modem Cable 연결 4. Target Computer, Host Computer 2015-05-28 10
2. Device Driver 작업환경은? : Windbg 설치 1. 먼저두대의컴퓨간에널모뎀케이블과하이퍼터미널을이용하여통신여부를파악한다. (buadrate, no hardware 로세팅하여확인하며, 또한파일전송여부가잘되는지도확인하면좋을듯 ) 2. Target 컴퓨터의 OS 시스템이설치된하드디스크 (C:) 폴더에있는 BOOT.INI 파일의내용을다음과같이수정한다. 물론 baudrate 와 comport 값을적절하게세팅하여야한다. [boot loader] timeout=10 default=multi(0)disk(0)rdisk(0)partition(1)\winnt [operating systems] multi(0)disk(0)rdisk(0)partition(1)\winnt="microsoft Windows 2000 Professional" /fastdetect /noguiboot multi(0)disk(0)rdisk(0)partition(1)\winnt="ms Win 2000 Professional-Prof.Ham" /fastdetect /noguiboot /debug /debugport=com1 /baudrate=115200 2015-05-28 11
2. Device Driver 작업환경은? : Windbg 설치 3. Host Computer 에 Windbg 6.0 버전을설치한다 4. Target 컴퓨터에서작성된 *.pdb 파일을 Host computer 의 c:\winnt\ 아래 ( 중요?? : c:\winnt\symbolham) 에폴더를만들어복사한다. 5. Target 컴퓨터에서작성된 *.c, *.cpp 파일을 Host computer 의 c:\winnt\ 아래 ( 중요??: c:\winnt\symolsourceham) 에폴더를만들어복사한다. 6. Null Modem Cable 을연결하고난후, Host Computer 의 Windbg 를수행한다 7. Windbg 의 FILE->Symbol File Path 와 FILE->Source File Path 를 4, 5 에서의폴더로세팅한다 8. Windbg 의 Kernel Debug 를선택한다 9. 이제 Target Computer 를부팅한다. 10. Windbg 의 Command 창에디벅메시지가나타나는지를살펴본다 2015-05-28 12
2. Device Driver 작업환경은? : Windbg 설치 11. 가급적 Windbg 의 Debug->Source Mode 가체크되어있는지를확인한다 12. Windbg 의 Command 창에 " LM " 명령어를입력하여, 현재 Load 된 Module 들에대한상태들을살펴본다. 이때분석하고자하는드라이버들에대한 Symbol 들이잘올라가있는지를살펴본다 13. 12 번이여의치않은경우 ".reload " 명령어를입력하여, 새로운 Symbol 들로다시재로드하여, 원하는드라이버루틴에대한 *.pdb 파일들이제대로 Loading 되었는지를살펴본다 14. WIndbg 의 Command 창에서의명령에대하여서는 Windbg 의 Help- >Contents 를크릭하여도움말을열고난후 Reference->Debugger Commands 부분을읽어보면좋을듯하다. 2015-05-28 13
2. Device Driver 작업환경은? : Windbg 설치 15. 16. Windbg 의 Command 창에 " x i8042prt!* " 명령어를입력하여, i8042prt.sys 드라이버모듈과관련된 Symbols 들을살펴보기를바란다. \ 16. Windbg 의 Command 창에 " bp i8042prt!i8042keyboardinterruptservice* " 명령어를입력하여, Debug Break Point 를세팅한후, 그결과를체크하기위하여, " BL " 명령어를입력하여본다. " BC #", " BD # ", " BE # " 명령어는해당되는 Break Point 를지우거나, Disable, Enable 시킨다 17. Host Computer 에서 Break 하기위하여서는 Debug->Break 을선택하면된다 2015-05-28 14
1. 장치관리자란? 2. Device Driver 작업환경은? 3. Driver 의구조 4. Plug & Play 5. Device Driver 응용사례 : UsbBulk.sys 6. Application Program 2015-05-28 15
Driver 의구조 : Layered Driver Architecture Applications User Mode Win32 API User Mode Client Driver Kernel Mode Kernel Mode Client Driver Operating System Kernel Class Driver File System Drivers Port Driver Hardware Bus driver 2015-05-28 16
2015-05-28 17
1. 장치관리자란? 2. Device Driver 작업환경은? 3. Driver 의구조 4. Plug & Play 5. Device Driver 응용사례 : UsbBulk.sys 6. Application Program 2015-05-28 18
PCI bus : PCI bus driver BUS Driver & Function Driver One PCI Bus driver makes a thread which monitoring the attachment or dettachment of the device by sending spcial command to all the device on PCI bus All the device should send a data packet such as PID, VID With the information of PID and VID, OS (Windows xp) is searching a *.inf file thai is located in C:\windows\inf Based on *.inf file, OS loading(install) a device driver ( *.sys) 2015-05-28 19
INF file: (VID, PID) [Version] Signature="$CHICAGO$" Class=USB ClassGUID={36FC9E60-C465-11CF-8056-444553540000} provider=%providername% DriverVer=10/23/2006 [SourceDisksNames] 1="USB Downloader Installation Disk for SEC SOC",,, [SourceDisksFiles] SECUSB2.sys = 1 SECUSB2.inf = 1 [Manufacturer] %MfgName%=SystemLsi [SystemLsi] %USB\VID_04E8&PID_1234.DeviceDesc%=SECUSB2.Dev, USB\VID_04E8&PID_6400 2015-05-28 20
INF file: (VID, PID) [DestinationDirs] SECUSB2.Files.Ext = 10,System32\Drivers SECUSB2.Files.Inf = 10,INF [SECUSB2.Dev] CopyFiles=SECUSB2.Files.Ext, SECUSB2.Files.Inf AddReg=SECUSB2.AddReg [SECUSB2.Dev.NT] CopyFiles=SECUSB2.Files.Ext, SECUSB2.Files.Inf AddReg=SECUSB2.AddReg [SECUSB2.Dev.NT.Services] Addservice = SECUSB2, 0x00000002, SECUSB2.AddService 2015-05-28 21
INF file: (VID, PID) [SECUSB2.AddService] DisplayName = %SECUSB2.SvcDesc% ServiceType = 1 ; SERVICE_KERNEL_DRIVER StartType = 3 ; SERVICE_DEMAND_START ErrorControl = 1 ; SERVICE_ERROR_NORMAL ServiceBinary = %10%\System32\Drivers\SECUSB2.sys LoadOrderGroup = Base [SECUSB2.AddReg] HKR,,DevLoader,,*ntkern HKR,,NTMPDriver,,SECUSB2.sys HKLM,"System\Currentcontrolset\Services\SECUSB2\Parameters","MaximumTransferSize", 0x10001,4096 HKLM,"System\Currentcontrolset\Services\SECUSB2\Parameters","DebugLevel",0x10001,2 [SECUSB2.Files.Ext] SECUSB2.sys [SECUSB2.Files.Inf] SECUSB2.Inf 2015-05-28 22
INF file: (VID, PID) ;---------------------------------------------------------------; [Strings] ProviderName="SEC AP application Team" MfgName="SEC, SYSTEM LSI" USB\VID_04E8&PID_1234.DeviceDesc="SEC SOC SMDK Board" SECUSB2.SvcDesc="SECUSB2.sys, SEC SOC USBD Driver 2015-05-28 23
1. 장치관리자란? 2. Device Driver 작업환경은? 3. Driver 의구조 4. Plug & Play 5. Device Driver 응용사례 : UsbBulk.sys 6. Application Program 2015-05-28 24
파일의구성 1. Bulkusb.c 2. Bulkpnp.c 3. Busbdbg.c 4. Ioctlblk.c 5. Ocrwblk.c 6. Bulkpwr.c 2015-05-28 25
Sources 파일 TARGETNAME=secbulk TARGETTYPE=DRIVER DRIVERTYPE=WDM TARGETPATH=obj TARGETLIBS=$(DDK_LIB_PATH)\usbd.lib USE_MAPSYM=1 SOURCES= \ BulkUsb.rc \ BusbDbg.c \ BulkUsb.c \ SBulkPnP.c \ BulkPwr.c \ IoctlBlk.c \ OcrwBlk.c 2015-05-28 26
Bulkusb.c : DriverEntry() NTSTATUS DriverEntry( IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath ) { // Create dispatch points for create, close, unload DriverObject->MajorFunction[IRP_MJ_CREATE] = BulkUsb_Create; DriverObject->MajorFunction[IRP_MJ_CLOSE] = BulkUsb_Close; DriverObject->DriverUnload = BulkUsb_Unload; CreateFile() CloseFile() DeviceIOControl() // User mode DeviceIoControl() calls will be routed here DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = BulkUsb_ProcessIOCTL; // User mode ReadFile()/WriteFile() calls will be routed here DriverObject->MajorFunction[IRP_MJ_WRITE] = BulkUsb_Write; DriverObject->MajorFunction[IRP_MJ_READ] = BulkUsb_Read; // routines for handling system PNP and power management requests DriverObject->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = BulkUsb_ProcessSysControlIrp; DriverObject->MajorFunction[IRP_MJ_PNP] = BulkUsb_ProcessPnPIrp; DriverObject->MajorFunction[IRP_MJ_POWER] = BulkUsb_ProcessPowerIrp;.. IoCallDriver() WriteFile() ReadFile() PowerManager 2015-05-28 27 PnPManager
Bulkusb.c // DriverObject->DriverExtension->AddDevice = BulkUsb_PnPAddDevice; BULKUSB_KdPrint( DBGLVL_DEFAULT,("exiting DriverEntry (%x)\n", ntstatus)); } return ntstatus; 장치가장착될경우에 PnP Manager 에의하여불리어진다. 2015-05-28 28
Bulkusb.c : BulkUsb_ProcessSysControlIrp NTSTATUS BulkUsb_ProcessSysControlIrp( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; irpstack = IoGetCurrentIrpStackLocation (Irp); deviceextension = DeviceObject->DeviceExtension; stackdeviceobject = deviceextension->topofstackdeviceobject; BulkUsb_IncrementIoCount(DeviceObject); BULKUSB_ASSERT( IRP_MJ_SYSTEM_CONTROL == irpstack->majorfunction ); IoCopyCurrentIrpStackLocationToNext(Irp); ntstatus = IoCallDriver(stackDeviceObject, Irp); BulkUsb_DecrementIoCount(DeviceObject); } return ntstatus; Next Lower Driver Drivers that do not support WMI by registering as a WMI data provider must pass IRP_MJ_SYSTEM_CONTROL requests to the next lower driver. 2015-05-28 29
Bulkusb.c : BulkUsb_Read NTSTATUS BulkUsb_Read( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp ) { } NTSTATUS ntstatus = BulkUsb_StagedReadWrite(DeviceObject, Irp, TRUE); // false to write, true to read return ntstatus; 2015-05-28 30
Bulkusb.c : BulkUsb_StagedReadWrite NTSTATUS BulkUsb_StagedReadWrite( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp, IN BOOLEAN Read ) { Maximum TransferSize:4096 PDEVICE_EXTENSION deviceextension = DeviceObject->DeviceExtension; if ( Irp->MdlAddress ) { // could be NULL for 0-len request totallength = MmGetMdlByteCount(Irp->MdlAddress); } if ( totallength <= deviceextension->maximumtransfersize ) { // for short or zero-len transfers, no need to do the staging; do it in a single request return BulkUsb_SingleUrbReadWrite( DeviceObject, Irp, Read ); } } 2015-05-28 31
Bulkusb.c : BulkUsb_SingleUrbReadWrite()-1 NTSTATUS BulkUsb_SingleUrbReadWrite( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp, IN BOOLEAN Read) { Irp->IoStatus.Information = 0; siz = sizeof(struct _URB_BULK_OR_INTERRUPT_TRANSFER); irpstack = IoGetCurrentIrpStackLocation (Irp); fileobject = irpstack->fileobject; pipehandle = fileobject->fscontext;.. if ( Irp->MdlAddress ) { // could be NULL for 0-len request totallength = MmGetMdlByteCount(Irp->MdlAddress); } urb = BulkUsb_BuildAsyncRequest(DeviceObject, Irp, pipehandle, Read); deviceextension->baseurb = urb; nextstack = IoGetNextIrpStackLocation(Irp); nextstack->parameters.others.argument1 = urb; 2015-05-28 32
Bulkusb.c : BulkUsb_SingleUrbReadWrite()-2 nextstack->majorfunction = IRP_MJ_INTERNAL_DEVICE_CONTROL; nextstack->parameters.deviceiocontrol.iocontrolcode = IOCTL_INTERNAL_USB_SUBMIT_URB; IoSetCompletionRoutine( Irp, // irp to use BulkUsb_SimpleReadWrite_Complete, // routine to call when irp is done DeviceObject, // we pass our FDO as context to pass routine TRUE, // call on success TRUE, // call on error TRUE); BulkUsb_IncrementIoCount(DeviceObject); } ntstatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp ); return ntstatus; 2015-05-28 33
Data Structure : IRP typedef struct _IRP {.. Pointer to an MDL describing a user buffer for an PMDL MdlAddress; IRP_MJ_READ or IRP_MJ_WRITE request if the ULONG Flags; driver set up its device object(s) for direct I/O. union { struct _IRP *MasterIrp;.. PVOID SystemBuffer; } AssociatedIrp;.. IO_STATUS_BLOCK IoStatus;.. AssociatedIrp.SystemBuffer PDRIVER_CANCEL CancelRoutine; Pointer to a system-space buffer for one of the PVOID UserBuffer;.. } Tail; } IRP, *PIRP; following: (1) a transfer request to a driver that set up its device object(s) requesting buffered I/O; (2) an IRP_MJ_DEVICE_CONTROL request, (3) an IRP_MJ_INTERNAL_DEVICE_CONTROL request with an I/O control code that was 2015-05-28 34 defined with METHOD_BUFFERED
Data Structure : IO_STACK_LOCATION typedef struct _IO_STACK_LOCATION { UCHAR MajorFunction; UCHAR MinorFunction; UCHAR Flags; UCHAR Control; union { // Parameters for IRP_MJ_CREATE struct { PIO_SECURITY_CONTEXT SecurityContext; ULONG Options; USHORT POINTER_ALIGNMENT FileAttributes; USHORT ShareAccess; ULONG POINTER_ALIGNMENT EaLength; } Create; // Parameters for IRP_MJ_READ struct { ULONG Length; ULONG POINTER_ALIGNMENT Key; LARGE_INTEGER ByteOffset; } Read;. PDEVICE_OBJECT DeviceObject; PFILE_OBJECT FileObject;.. } IO_STACK_LOCATION, *PIO_STACK_LOCATION; 2015-05-28 35
Data Structure : FILE_OBJECT Accessible Fields PDEVICE_OBJECT DeviceObject Pointer to the device object on which the file is opened. PVOID FsContext Pointer to whatever optional state a driver maintains about the file object; otherwise, NULL. PVOID FsContext2 Pointer to whatever additional state a driver maintains about the file object; otherwise, NULL. UNICODE_STRING FileName Is the name of the file opened on the device, or the Length of the string is zero if the device represented by DeviceObject is being opened. 2015-05-28 36
2015-05-28 37
2015-05-28 38
2015-05-28 39
1. 장치관리자란? 2. Device Driver 작업환경은? 3. Driver 의구조 4. Plug & Play 5. Device Driver 응용사례 : UsbBulk.sys 6. Application Program 2015-05-28 40
Application Program 아지시스템에서제공하는 2410 관련 CD 에들어있는 rwbulk.exe ( Web Disk 에서다운로드할것 ) 1. MBA 2440 보드를호스트컴퓨터와연결 2. 호스트컴퓨터에서 DNW.exe 를가동하고 MBA 를리셋한후 18 번메뉴를선택한후에다시 1 번메뉴를세팅하여 target MBA 2440 보드의 USB Client (Device) 기능을발휘시킨다. 3. 호스트컴퓨터의 rwbulk.exe 를가동한후 rwbulk r 128 을수행하여타겟 MBA2440 으로부터 USB 를통하여 data 를전송받아본다. 4. 3. 단계가잘되지않을경우, dnw.exe 의 USB Port-> Rx Test 를클릭하여타겟 MBA2440 으로부터 USB 룰통하여 data 가잘전송되는지체크하여본다. 2015-05-28 41
Application Program DNW.exe 프로그램의작동 : USB Port-> Rx Test 2015-05-28 42
Application Program Rwbulk.exe 프로그램의작동 : rwbulk r 128 2015-05-28 43
Application Program Rwbulk.exe 프로그램이작동될때, dnw.exe 도 MBA2440 보드가 USB Device 로작동되게하기위하여가동되어야하며, 여기서 18 번메뉴와이에대한 1 번서브를선택하여야한다. 이러한처리가있어야만 MBA2440 보드가 usb Device 로가동되며, 따라서이때 dnw.exe 의 USB Port -> Rx Test 를수행하여 MBA2440 보드의 USB Device 기능이잘발휘되는가를살펴본다. 다음그림에서는 SECBULK.SYS 와관련하여두개의장치가가동중임을알수있으며, 하나는 DNW.exe 와다른하나는 rwbulk.exe 와 SECBULK.SYS 와연계하여작동하고있음을보여주고있다. USBPDO-12 2015-05-28 44
Application Program USB Client 의 장치명 2개가 사용되고 있다. 2015-05-28 45
Application Program rwbulk.c 에대하여 MS Visual C 로작동시키기위한절차 1. rwbulk.c 를 MS Visual C tool 을이용하여 open 한다. 2. Visual C 상황에서 Build->Rebuild ALL 를수행하여본다. 이후 Project 를만들것이냐? 물음이들어오면 yes 를응답한다. 3. 다시 Visual C 상황에서 Build->Rebuild ALL 를수행하여본다. 당연히 ERROR 가발생된다. ERROR 에대처한다음절차를밟는다 4. Tools->Options 를선택하여 Build Directory 탭을선정하고 include files 에대한 directory 를 D:\WINDDK\2600.1106\INC\DDK\WXP 로세팅한다. 5. Project->Settings 를클릭하고나서나타나는대화상자에서 Link 탭을선정한다. 그리고나서 Object/Library modules 부분에 setupapi.lib usbd.lib 를추가한다. 6. Tools->Options 를선택하여 Build Directory 탭을선정하고 library files 에대한directory를 D:\WINDDK\2600.1106\LIB\WXP\I386로세팅한다. 2015-05-28 46
Application Program rwbulk.c 에대하여 MS Visual C 로작동시키기위한절차 7. Project->Settings 의 Debug 탭을선택하고 Program Argument 에 r 128 을입력한다. 8. Rwbulk.c 의 main() 함수의 parse() 부분에 debug break 을세팅하고나서 build->start debug 을수행하면서디버깅하여본다. 2015-05-28 47
Application Program 2015-05-28 48
Application Program 다음과같이기존의 main() 루틴에 dump() 를추가하여 USB Device 로부터읽어온내용을 command 창에나타낸다. printf("<%s> R (%04.4d) : request %06.6d bytes -- %06.6d bytes read\n", inpipe, i, ReadLen, nbytesread); //HAM printf("dumping read buffer\n"); dump( pinbuf, nbytesread ); //HAM if (fwrite) {.. 2015-05-28 49
Application Program 2015-05-28 50
Application Program TIP : 디버깅모드에서작동시키면작동이되지않음을유의하시기바랍니다. 따라서 USB read 작동시는디버깅상태에서 Test 가되지않음을유념하시기바랍니다. 2015-05-28 51
- END - 2015-05-28 52