diff options
Diffstat (limited to 'general')
196 files changed, 22630 insertions, 81 deletions
diff --git a/general/DCHU/README.md b/general/DCHU/README.md new file mode 100644 index 00000000..bf74d451 --- /dev/null +++ b/general/DCHU/README.md @@ -0,0 +1,41 @@ +<!--- + name: DHCU - Driver package installation toolkit for universal drivers + platform: UMDF2 + language: cpp + category: General DHCU + description: Illustrates DCHU principles of universal driver design. + samplefwlink: https://aka.ms/sceeqq +---> + + +# Driver package installation toolkit for universal drivers + +This sample illustrates the DCHU principles of universal driver design. The sample uses the [OSR FX2 learning kit](http://store.osr.com/product/osr-usb-fx2-learning-kit-v2/). For a detailed code walkthrough, see [Universal Driver Scenarios](https://docs.microsoft.com/windows-hardware/drivers/develop/universal-driver-scenarios). + +There are three Visual Studio solutions in this sample. Each one represents a single submission on the [Windows Hardware Dev Center dashboard](https://developer.microsoft.com/windows/hardware/dashboard-sign-in). The solutions are split into the following subdirectories: + +* `osrfx2_DCHU_base` : The driver for the OSR FX2 Learning Kit. This includes the device driver, an upper filter driver for the device (a no-op), a Win32 User Service that controls lights on the device, and a console app that can control the device. + +* `osrfx2_DCHU_extension_loose`: An extension INF for the OSR FX2 device. This extension modifies some registry settings originally specified by the base driver (`osrfx2_DCHU_base`) and also uses AddComponent to create a Software Component. There is also a component INF project that would be a separate submission to DevCenter, which runs some simple software. These two projects are loosely coupled, and can be installed in any order on the machine. + +* `osrfx2_DCHU_extension_tight`: An extension INF for the OSR FX2 device. This extension mimics the behavior of `osrfx2_DCHU_extension_loose`; however, it does so in a tightly coupled manner. Using CopyINF, both the extension and component INF are placed into one driver package (and one submission to DevCenter). Here there is less flexibility with the base/component/extension relationship, but it ensures that the component INF is applied at the same time as the extension. + +Both `osrfx2_DCHU_extension_loose` and `osrfx2_DCHU_extension_tight` provide the same functionality, so installing both on the same OSR FX2 device is unnecessary. They are intended to show a different way to use extension and component INF's depending on a project's needs. + +NOTE: osrfx2_DCHU_extension_tight will not currently build on Windows 10 version 1703. You will see an error saying that the directive CopyINF does not work from extension INFs. This has been fixed for the Windows 10 Fall Creators Update. + +Each of these solutions can be built with the latest WDK on Visual Studio 2015. Additionally, you can also download a [Universal Windows Platform app (UWP)](https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/CustomCapability) that controls the OSR FX2 Learning Kit's device. To learn how to pair a UWP app with a device, see [Hardware access for Universal Windows Platform apps](https://docs.microsoft.com/windows-hardware/drivers/devapps/hardware-access-for-universal-windows-platform-apps) + +The app and the contents of this sample can coexist, but on Windows 10 version 1703, to build the app with Visual Studio 2017, the computer cannot have the WDK installed. + +To install these driver packages, make sure that the target machine is in Test Mode, using `bcdedit /set testsigning on`. + +Then, use `pnputil /i /a <PATHTOINF>` to install each of the desired driver packages. They should +be installed in the following order: + +* `osrfx2_DCHU_base` +* `osrfx2_DCHU_extension` +* `osrfx2_DCHU_component` + +Technically the order of `osrfx2_DCHU_extension` and `osrfx2_DCHU_component` doesn't matter, but the software within `osrfx2_DCHU_component` will read the registry set by the extension to show that an extension INF's settings are applied *after* the base INF's. + diff --git a/general/DCHU/osrfx2_DCHU_base/deviceMetadata/B4D697F5-1C56-4807-ACCD-B28C09D37FF0.devicemetadata-ms b/general/DCHU/osrfx2_DCHU_base/deviceMetadata/B4D697F5-1C56-4807-ACCD-B28C09D37FF0.devicemetadata-ms Binary files differnew file mode 100644 index 00000000..5f8e82ee --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/deviceMetadata/B4D697F5-1C56-4807-ACCD-B28C09D37FF0.devicemetadata-ms diff --git a/general/DCHU/osrfx2_DCHU_base/inc/prototypes.h b/general/DCHU/osrfx2_DCHU_base/inc/prototypes.h new file mode 100644 index 00000000..cc99cdfe --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/inc/prototypes.h @@ -0,0 +1,14 @@ +DRIVER_INITIALIZE DriverEntry; + +EVT_WDF_DRIVER_DEVICE_ADD EvtDeviceAdd; + +EVT_WDF_DEVICE_CONTEXT_CLEANUP EvtDriverContextCleanup; +EVT_WDF_DEVICE_PREPARE_HARDWARE EvtDevicePrepareHardware; + +EVT_WDF_IO_QUEUE_IO_READ EvtIoRead; +EVT_WDF_IO_QUEUE_IO_WRITE EvtIoWrite; +EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL EvtIoDeviceControl; + +EVT_WDF_REQUEST_COMPLETION_ROUTINE EvtRequestReadCompletionRoutine; +EVT_WDF_REQUEST_COMPLETION_ROUTINE EvtRequestWriteCompletionRoutine; + diff --git a/general/DCHU/osrfx2_DCHU_base/inc/public.h b/general/DCHU/osrfx2_DCHU_base/inc/public.h new file mode 100644 index 00000000..f1fc6be3 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/inc/public.h @@ -0,0 +1,173 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + public.h + +Abstract: + +Environment: + + User & Kernel mode + +--*/ + +#ifndef _PUBLIC_H +#define _PUBLIC_H + +#include <initguid.h> + +// {573E8C73-0CB4-4471-A1BF-FAB26C31D384} +DEFINE_GUID(GUID_DEVINTERFACE_OSRUSBFX2, + 0x573e8c73, 0xcb4, 0x4471, 0xa1, 0xbf, 0xfa, 0xb2, 0x6c, 0x31, 0xd3, 0x84); + +#pragma warning(push) +#pragma warning(disable:4201) // nameless struct/union +#pragma warning(disable:4214) // bit field types other than int + +// +// Define the structures that will be used by the IOCTL +// interface to the driver +// + +// +// BAR_GRAPH_STATE +// +// BAR_GRAPH_STATE is a bit field structure with each +// bit corresponding to one of the bar graph on the +// OSRFX2 Development Board +// +#include <pshpack1.h> +typedef struct _BAR_GRAPH_STATE { + + union { + + struct { + // + // Individual bars starting from the + // top of the stack of bars + // + // NOTE: There are actually 10 bars, + // but the very top two do not light + // and are not counted here + // + UCHAR Bar1 : 1; + UCHAR Bar2 : 1; + UCHAR Bar3 : 1; + UCHAR Bar4 : 1; + UCHAR Bar5 : 1; + UCHAR Bar6 : 1; + UCHAR Bar7 : 1; + UCHAR Bar8 : 1; + }; + + // + // The state of all the bar graph as a single + // UCHAR + // + UCHAR BarsAsUChar; + + }; + +}BAR_GRAPH_STATE, *PBAR_GRAPH_STATE; + +// +// SWITCH_STATE +// +// SWITCH_STATE is a bit field structure with each +// bit corresponding to one of the switches on the +// OSRFX2 Development Board +// +typedef struct _SWITCH_STATE { + + union { + struct { + // + // Individual switches starting from the + // left of the set of switches + // + UCHAR Switch1 : 1; + UCHAR Switch2 : 1; + UCHAR Switch3 : 1; + UCHAR Switch4 : 1; + UCHAR Switch5 : 1; + UCHAR Switch6 : 1; + UCHAR Switch7 : 1; + UCHAR Switch8 : 1; + }; + + // + // The state of all the switches as a single + // UCHAR + // + UCHAR SwitchesAsUChar; + + }; + + +}SWITCH_STATE, *PSWITCH_STATE; + +#include <poppack.h> + +#pragma warning(pop) + +#define IOCTL_INDEX 0x800 +#define FILE_DEVICE_OSRUSBFX2 65500U + +#define IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX, \ + METHOD_BUFFERED, \ + FILE_READ_ACCESS) + +#define IOCTL_OSRUSBFX2_RESET_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 1, \ + METHOD_BUFFERED, \ + FILE_WRITE_ACCESS) + +#define IOCTL_OSRUSBFX2_REENUMERATE_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 3, \ + METHOD_BUFFERED, \ + FILE_WRITE_ACCESS) + +#define IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ + IOCTL_INDEX + 4, \ + METHOD_BUFFERED, \ + FILE_READ_ACCESS) + + +#define IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ + IOCTL_INDEX + 5, \ + METHOD_BUFFERED, \ + FILE_WRITE_ACCESS) + + +#define IOCTL_OSRUSBFX2_READ_SWITCHES CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 6, \ + METHOD_BUFFERED, \ + FILE_READ_ACCESS) + + +#define IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 7, \ + METHOD_BUFFERED, \ + FILE_READ_ACCESS) + + +#define IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 8, \ + METHOD_BUFFERED, \ + FILE_WRITE_ACCESS) + +#define IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ + IOCTL_INDEX + 9, \ + METHOD_OUT_DIRECT, \ + FILE_READ_ACCESS) + +#endif diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base.sln b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base.sln new file mode 100644 index 00000000..dfa90dbd --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base.sln @@ -0,0 +1,103 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 12.0 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "osrfx2_DCHU_base", "osrfx2_DCHU_base", "{3B268182-F450-4AB8-B350-A2CF6495F756}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "osrfx2_DCHU_testapp", "osrfx2_DCHU_testapp", "{52ABC41E-9AAA-4DA8-8986-F6298E32C8A3}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrfx2_DCHU_base", "osrfx2_DCHU_base\osrfx2_DCHU_base.vcxproj", "{5B711254-3F53-4E1D-A1AD-CC81E34588B7}" + ProjectSection(ProjectDependencies) = postProject + {3CC42473-D121-41F4-AE26-1F2F0AC65E82} = {3CC42473-D121-41F4-AE26-1F2F0AC65E82} + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3} = {DE70E2D1-6A4D-4984-BD82-CE750889F0D3} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrfx2_DCHU_testapp", "osrfx2_DCHU_testapp\osrusbfx2.vcxproj", "{6EED5CDD-5526-40DC-97F9-582857E10187}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "osrfx2_DCHU_filter", "osrfx2_DCHU_filter", "{1665ED66-7966-4FE2-9BA5-B5843511E325}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrfx2_DCHU_filter", "osrfx2_DCHU_filter\osrfx2_DCHU_filter.vcxproj", "{3CC42473-D121-41F4-AE26-1F2F0AC65E82}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "osrfx2_DCHU_usersvc", "osrfx2_DCHU_usersvc", "{DA04929E-1AFF-4EB7-935F-E9485C0316DB}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrfx2_DCHU_usersvc", "osrfx2_DCHU_usersvc\osrfx2_DCHU_usersvc.vcxproj", "{DE70E2D1-6A4D-4984-BD82-CE750889F0D3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|ARM64 = Debug|ARM64 + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|ARM = Release|ARM + Release|ARM64 = Release|ARM64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Debug|ARM.ActiveCfg = Debug|Win32 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Debug|ARM64.ActiveCfg = Debug|Win32 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Debug|Win32.ActiveCfg = Debug|Win32 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Debug|Win32.Build.0 = Debug|Win32 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Debug|Win32.Deploy.0 = Debug|Win32 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Debug|x64.ActiveCfg = Debug|x64 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Debug|x64.Build.0 = Debug|x64 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Debug|x64.Deploy.0 = Debug|x64 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Release|ARM.ActiveCfg = Release|Win32 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Release|ARM64.ActiveCfg = Release|Win32 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Release|Win32.ActiveCfg = Release|Win32 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Release|Win32.Build.0 = Release|Win32 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Release|Win32.Deploy.0 = Release|Win32 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Release|x64.ActiveCfg = Release|x64 + {5B711254-3F53-4E1D-A1AD-CC81E34588B7}.Release|x64.Build.0 = Release|x64 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Debug|ARM.ActiveCfg = Debug|Win32 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Debug|ARM64.ActiveCfg = Debug|Win32 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Debug|Win32.ActiveCfg = Debug|Win32 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Debug|Win32.Build.0 = Debug|Win32 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Debug|x64.ActiveCfg = Debug|x64 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Debug|x64.Build.0 = Debug|x64 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Release|ARM.ActiveCfg = Release|Win32 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Release|ARM64.ActiveCfg = Release|Win32 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Release|Win32.ActiveCfg = Release|Win32 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Release|Win32.Build.0 = Release|Win32 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Release|x64.ActiveCfg = Release|x64 + {6EED5CDD-5526-40DC-97F9-582857E10187}.Release|x64.Build.0 = Release|x64 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Debug|ARM.ActiveCfg = Debug|Win32 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Debug|ARM64.ActiveCfg = Debug|Win32 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Debug|Win32.ActiveCfg = Debug|Win32 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Debug|Win32.Build.0 = Debug|Win32 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Debug|Win32.Deploy.0 = Debug|Win32 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Debug|x64.ActiveCfg = Debug|x64 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Debug|x64.Build.0 = Debug|x64 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Debug|x64.Deploy.0 = Debug|x64 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Release|ARM.ActiveCfg = Release|Win32 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Release|ARM64.ActiveCfg = Release|Win32 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Release|Win32.ActiveCfg = Release|Win32 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Release|Win32.Build.0 = Release|Win32 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Release|Win32.Deploy.0 = Release|Win32 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Release|x64.ActiveCfg = Release|x64 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Release|x64.Build.0 = Release|x64 + {3CC42473-D121-41F4-AE26-1F2F0AC65E82}.Release|x64.Deploy.0 = Release|x64 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Debug|ARM.ActiveCfg = Debug|Win32 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Debug|ARM64.ActiveCfg = Debug|Win32 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Debug|Win32.ActiveCfg = Debug|Win32 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Debug|Win32.Build.0 = Debug|Win32 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Debug|x64.ActiveCfg = Debug|x64 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Debug|x64.Build.0 = Debug|x64 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Release|ARM.ActiveCfg = Release|Win32 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Release|ARM64.ActiveCfg = Release|Win32 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Release|Win32.ActiveCfg = Release|Win32 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Release|Win32.Build.0 = Release|Win32 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Release|x64.ActiveCfg = Release|x64 + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {5B711254-3F53-4E1D-A1AD-CC81E34588B7} = {3B268182-F450-4AB8-B350-A2CF6495F756} + {6EED5CDD-5526-40DC-97F9-582857E10187} = {52ABC41E-9AAA-4DA8-8986-F6298E32C8A3} + {3CC42473-D121-41F4-AE26-1F2F0AC65E82} = {1665ED66-7966-4FE2-9BA5-B5843511E325} + {DE70E2D1-6A4D-4984-BD82-CE750889F0D3} = {DA04929E-1AFF-4EB7-935F-E9485C0316DB} + EndGlobalSection +EndGlobal diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/Interrupt.c b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/Interrupt.c new file mode 100644 index 00000000..5573ef6e --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/Interrupt.c @@ -0,0 +1,206 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + Interrupt.c + +Abstract: + + This modules has routines configure a continuous reader on an + interrupt pipe to asynchronously read toggle switch states. + +Environment: + + User mode + +--*/ + +#include "osrusbfx2.h" + +#if defined(EVENT_TRACING) +#include "interrupt.tmh" +#endif + + +/*++ + +Routine Description: + + This routine configures a continuous reader on the + interrupt endpoint. It's called from the PrepareHarware event. + +Arguments: + + DeviceContext - The device context to use for configuration + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +OsrFxConfigContReaderForInterruptEndPoint( + _In_ PDEVICE_CONTEXT DeviceContext + ) +{ + WDF_USB_CONTINUOUS_READER_CONFIG ReaderConfig; + NTSTATUS Status; + + WDF_USB_CONTINUOUS_READER_CONFIG_INIT(&ReaderConfig, + OsrFxEvtUsbInterruptPipeReadComplete, + DeviceContext, + sizeof(UCHAR)); + + ReaderConfig.EvtUsbTargetPipeReadersFailed = OsrFxEvtUsbInterruptReadersFailed; + + // + // Reader requests are not posted to the target automatically. + // The driver must explictly call WdfIoTargetStart to kick start the + // reader. In this sample, it's done in D0Entry. + // By defaut, framework queues two requests to the target + // endpoint. Driver can configure up to 10 requests with CONFIG macro. + // + Status = WdfUsbTargetPipeConfigContinuousReader(DeviceContext->InterruptPipe, + &ReaderConfig); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "OsrFxConfigContReaderForInterruptEndPoint failed %x\n", + Status); + return Status; + } + + return Status; +} + + +/*++ + +Routine Description: + + This is the completion routine of the continuous reader. This can be called + concurrently on a multiprocessor system if there are multiple readers + configured, so make sure to protect access to global resources. + +Arguments: + + Buffer - This buffer is freed when this call returns. + If the driver wants to delay processing of the buffer, it + can take an additional referrence + + Context - Provided in the WDF_USB_CONTINUOUS_READER_CONFIG_INIT macro + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +VOID +OsrFxEvtUsbInterruptPipeReadComplete( + _In_ WDFUSBPIPE Pipe, + _In_ WDFMEMORY Buffer, + _In_ size_t NumBytesTransferred, + _In_ WDFCONTEXT Context + ) +{ + PUCHAR SwitchState = NULL; + WDFDEVICE Device; + PDEVICE_CONTEXT DeviceContext = Context; + + UNREFERENCED_PARAMETER(Pipe); + + Device = WdfObjectContextGetObject(DeviceContext); + + // + // Make sure that there is data in the read packet. Depending on the device + // specification, it is possible for it to return a 0 length read in + // certain conditions. + // + if (NumBytesTransferred == 0) + { + TraceEvents(TRACE_LEVEL_WARNING, DBG_INIT, + "OsrFxEvtUsbInterruptPipeReadComplete Zero length read " + "occured on the Interrupt Pipe's Continuous Reader\n"); + return; + } + + assert(NumBytesTransferred == sizeof(UCHAR)); + + SwitchState = WdfMemoryGetBuffer(Buffer, NULL); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, + "OsrFxEvtUsbInterruptPipeReadComplete SwitchState %x\n", + *SwitchState); + + DeviceContext->CurrentSwitchState = *SwitchState; + + // + // Handle any pending Interrupt Message IOCTLs. Note that the OSR USB device + // will generate an interrupt message when the the device resumes from a low + // power state. So if the Interrupt Message IOCTL was sent after the device + // has gone to a low power state, the pending Interrupt Message IOCTL will + // get completed in the function call below, before the user twiddles the + // dip switches on the OSR USB device. If this is not the desired behavior + // for your driver, then you could handle this condition by maintaining a + // state variable on D0Entry to track interrupt messages caused by power up. + // + OsrUsbIoctlGetInterruptMessage(Device, STATUS_SUCCESS); + +} + + +/*++ + +Routine Description: + + This the failure routine of the continous reader. + +Arguments: + + Pipe - The pipe that failed creation + + Status - The failure NTSTATUS + + UsbdStatus - A USB specific error code + +Return Value: + + TRUE + +--*/ +BOOLEAN +OsrFxEvtUsbInterruptReadersFailed( + _In_ WDFUSBPIPE Pipe, + _In_ NTSTATUS Status, + _In_ USBD_STATUS UsbdStatus + ) +{ + WDFDEVICE Device = WdfIoTargetGetDevice(WdfUsbTargetPipeGetIoTarget(Pipe)); + PDEVICE_CONTEXT DeviceContext = GetDeviceContext(Device); + + UNREFERENCED_PARAMETER(UsbdStatus); + + // + // Clear the current switch state. + // + DeviceContext->CurrentSwitchState = 0; + + // + // Service the pending interrupt switch change request + // + OsrUsbIoctlGetInterruptMessage(Device, Status); + + return TRUE; +} + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/bulkrwr.c b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/bulkrwr.c new file mode 100644 index 00000000..d29dea0b --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/bulkrwr.c @@ -0,0 +1,476 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + bulkrwr.c + +Abstract: + + This file has routines to perform reads and writes. + The read and writes are targeted bulk to endpoints. + +Environment: + + User mode + +--*/ + +#include "osrusbfx2.h" + + +#if defined(EVENT_TRACING) +#include "bulkrwr.tmh" +#endif + +#pragma warning(disable:4267) + + +/*++ + +Routine Description: + + Called by the framework when it receives Read or Write requests. + +Arguments: + + Queue - Default queue handle + + Request - Handle to the read/write request + + Length - Length of the data buffer associated with the request. + The default property of the queue is to not dispatch + zero lenght read & write requests to the driver and + complete is with status success. So we will never get + a zero length request + +Return Value: + + VOID + +--*/ +VOID +OsrFxEvtIoRead( + _In_ WDFQUEUE Queue, + _In_ WDFREQUEST Request, + _In_ size_t Length + ) +{ + WDFUSBPIPE Pipe; + NTSTATUS Status; + WDFMEMORY RequiredMemory; + PDEVICE_CONTEXT DeviceContext; + + UNREFERENCED_PARAMETER(Queue); + + // + // Log read start event, using IRP activity ID if available or request + // handle otherwise. + // + EventWriteReadStart(WdfIoQueueGetDevice(Queue), (ULONG)Length); + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "-->OsrFxEvtIoRead\n"); + + // + // First validate input parameters. + // + if (Length > TEST_BOARD_TRANSFER_BUFFER_SIZE) { + TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "Transfer exceeds %d\n", + TEST_BOARD_TRANSFER_BUFFER_SIZE); + Status = STATUS_INVALID_PARAMETER; + goto Exit; + } + + DeviceContext = GetDeviceContext(WdfIoQueueGetDevice(Queue)); + + Pipe = DeviceContext->BulkReadPipe; + + Status = WdfRequestRetrieveOutputMemory(Request, &RequiredMemory); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, + "WdfRequestRetrieveOutputMemory failed %!STATUS!\n", Status); + goto Exit; + } + + // + // The format call validates to make sure that you are reading or + // writing to the right Pipe type, sets the appropriate transfer flags, + // creates an URB and initializes the request. + // + Status = WdfUsbTargetPipeFormatRequestForRead(Pipe, + Request, + RequiredMemory, + NULL // Offsets + ); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, + "WdfUsbTargetPipeFormatRequestForRead failed 0x%x\n", Status); + goto Exit; + } + + WdfRequestSetCompletionRoutine(Request, + EvtRequestReadCompletionRoutine, + Pipe); + // + // Send the request asynchronously. + // + if (WdfRequestSend(Request, + WdfUsbTargetPipeGetIoTarget(Pipe), + WDF_NO_SEND_OPTIONS) == FALSE) + { + // + // Framework couldn't send the request for some reason. + // + TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfRequestSend failed\n"); + Status = WdfRequestGetStatus(Request); + goto Exit; + } + +Exit: + + if (!NT_SUCCESS(Status)) + { + // + // Log event read failed. + // + EventWriteReadFail(WdfIoQueueGetDevice(Queue), Status); + WdfRequestCompleteWithInformation(Request, Status, 0); + } + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ, "<-- OsrFxEvtIoRead\n"); + + return; +} + + +/*++ + +Routine Description: + + This is the completion routine for reads + If the irp completes with success, we check if we + need to recirculate this irp for another stage of + transfer. + +Arguments: + + Context - Driver supplied context + + Device - Device handle + + Request - Request handle + + Params - request completion params + +Return Value: + + VOID + +--*/ +VOID +EvtRequestReadCompletionRoutine( + _In_ WDFREQUEST Request, + _In_ WDFIOTARGET Target, + _In_ PWDF_REQUEST_COMPLETION_PARAMS CompletionParams, + _In_ WDFCONTEXT Context + ) +{ + NTSTATUS Status; + size_t BytesRead = 0; + PWDF_USB_REQUEST_COMPLETION_PARAMS UsbCompletionParams; + + UNREFERENCED_PARAMETER(Target); + UNREFERENCED_PARAMETER(Context); + + Status = CompletionParams->IoStatus.Status; + + UsbCompletionParams = CompletionParams->Parameters.Usb.Completion; + + BytesRead = UsbCompletionParams->Parameters.PipeRead.Length; + + if (NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ, + "Number of bytes read: %I64d\n", (INT64)BytesRead); + } + else + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, + "Read failed - request status 0x%x UsbdStatus 0x%x\n", + Status, UsbCompletionParams->UsbdStatus); + + } + + // + // Log read stop event, using IRP activity ID if available or request + // handle otherwise. + // + EventWriteReadStop(WdfIoQueueGetDevice(WdfRequestGetIoQueue(Request)), + BytesRead, + Status, + UsbCompletionParams->UsbdStatus); + + WdfRequestCompleteWithInformation(Request, Status, BytesRead); + + return; +} + + +/*++ + +Routine Description: + + Called by the framework when it receives Read or Write requests. + +Arguments: + + Queue - Default queue handle + + Request - Handle to the read/write request + + Lenght - Length of the data buffer associated with the request. + The default property of the queue is to not dispatch + zero lenght read & write requests to the driver and + complete is with status success. So we will never get + a zero length request + +Return Value: + + VOID + +--*/ +VOID +OsrFxEvtIoWrite( + _In_ WDFQUEUE Queue, + _In_ WDFREQUEST Request, + _In_ size_t Length + ) +{ + NTSTATUS Status; + WDFUSBPIPE Pipe; + WDFMEMORY RequiredMemory; + PDEVICE_CONTEXT DeviceContext; + + UNREFERENCED_PARAMETER(Queue); + + + // + // Log write start event, using IRP activity ID if available or request + // handle otherwise. + // + EventWriteWriteStart(WdfIoQueueGetDevice(Queue), (ULONG)Length); + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE, "-->OsrFxEvtIoWrite\n"); + + // + // First validate input parameters. + // + if (Length > TEST_BOARD_TRANSFER_BUFFER_SIZE) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, + "Transfer exceeds %d\n", + TEST_BOARD_TRANSFER_BUFFER_SIZE); + Status = STATUS_INVALID_PARAMETER; + goto Exit; + } + + DeviceContext = GetDeviceContext(WdfIoQueueGetDevice(Queue)); + + Pipe = DeviceContext->BulkWritePipe; + + Status = WdfRequestRetrieveInputMemory(Request, &RequiredMemory); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, + "WdfRequestRetrieveInputBuffer failed\n"); + goto Exit; + } + + Status = WdfUsbTargetPipeFormatRequestForWrite(Pipe, + Request, + RequiredMemory, + NULL // Offset + ); + + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, + "WdfUsbTargetPipeFormatRequestForWrite failed 0x%x\n", Status); + goto Exit; + } + + WdfRequestSetCompletionRoutine(Request, + EvtRequestWriteCompletionRoutine, + Pipe); + + // + // Send the request asynchronously. + // + if (WdfRequestSend(Request, + WdfUsbTargetPipeGetIoTarget(Pipe), + WDF_NO_SEND_OPTIONS) == FALSE) + { + // + // Framework couldn't send the request for some reason. + // + TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "WdfRequestSend failed\n"); + Status = WdfRequestGetStatus(Request); + goto Exit; + } + +Exit: + + if (!NT_SUCCESS(Status)) + { + // + // log event write failed. + // + EventWriteWriteFail(WdfIoQueueGetDevice(Queue), Status); + WdfRequestCompleteWithInformation(Request, Status, 0); + } + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE, "<-- OsrFxEvtIoWrite\n"); + + return; +} + + +/*++ + +Routine Description: + + This is the completion routine for writes + If the irp completes with success, we check if we + need to recirculate this irp for another stage of + transfer. + +Arguments: + + Context - Driver supplied context + + Device - Device handle + + Request - Request handle + + Params - request completion params + +Return Value: + + VOID + +--*/ +VOID +EvtRequestWriteCompletionRoutine( + _In_ WDFREQUEST Request, + _In_ WDFIOTARGET Target, + _In_ PWDF_REQUEST_COMPLETION_PARAMS CompletionParams, + _In_ WDFCONTEXT Context + ) +{ + NTSTATUS Status; + size_t BytesWritten = 0; + PWDF_USB_REQUEST_COMPLETION_PARAMS UsbCompletionParams; + + UNREFERENCED_PARAMETER(Target); + UNREFERENCED_PARAMETER(Context); + + Status = CompletionParams->IoStatus.Status; + + // + // For usb devices, we should look at the Usb.Completion param. + // + UsbCompletionParams = CompletionParams->Parameters.Usb.Completion; + + BytesWritten = UsbCompletionParams->Parameters.PipeWrite.Length; + + if (NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_WRITE, + "Number of bytes written: %I64d\n", + (INT64)BytesWritten); + } + else + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, + "Write failed: request status 0x%x UsbdStatus 0x%x\n", + Status, + UsbCompletionParams->UsbdStatus); + } + + // + // Log write stop event, using IRP activtiy ID if available or request + // handle otherwise. + // + EventWriteWriteStop(WdfIoQueueGetDevice(WdfRequestGetIoQueue(Request)), + BytesWritten, + Status, + UsbCompletionParams->UsbdStatus); + + WdfRequestCompleteWithInformation(Request, Status, BytesWritten); + + return; +} + + +/*++ + +Routine Description: + + This callback is invoked on every inflight request when the device + is suspended or removed. Since our inflight read and write requests + are actually pending in the target device, we will just acknowledge + its presence. Until we acknowledge, complete, or requeue the requests + framework will wait before allowing the device suspend or remove to + proceeed. When the underlying USB stack gets the request to suspend or + remove, it will fail all the pending requests. + +Arguments: + + Queue - Handle to queue object that is associated with the I/O request + + Request - Handle to a request object + + ActionFlags - Bitwise OR of one or more WDF_REQUEST_STOP_ACTION_FLAGS flags + +Return Value: + + VOID + +--*/ +VOID +OsrFxEvtIoStop( + _In_ WDFQUEUE Queue, + _In_ WDFREQUEST Request, + _In_ ULONG ActionFlags + ) +{ + UNREFERENCED_PARAMETER(Queue); + UNREFERENCED_PARAMETER(ActionFlags); + + if (ActionFlags & WdfRequestStopActionSuspend) + { + // + // Don't requeue. + // + WdfRequestStopAcknowledge(Request, FALSE); + } + else if(ActionFlags & WdfRequestStopActionPurge) + { + WdfRequestCancelSentRequest(Request); + } + return; +} + + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/device.c b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/device.c new file mode 100644 index 00000000..a32ab79e --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/device.c @@ -0,0 +1,1014 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + Device.c + +Abstract: + + USB device driver for OSR USB-FX2 Learning Kit + +Environment: + + User mode only + +--*/ + +#include "osrusbfx2.h" +#include <devpkey.h> + +#if defined(EVENT_TRACING) +#include "Device.tmh" +#endif + +#ifdef ALLOC_PRAGMA +#pragma alloc_text(PAGE, OsrFxEvtDeviceAdd) +#pragma alloc_text(PAGE, OsrFxEvtDevicePrepareHardware) +#pragma alloc_text(PAGE, OsrFxEvtDeviceD0Exit) +#pragma alloc_text(PAGE, SelectInterfaces) +#pragma alloc_text(PAGE, OsrFxSetPowerPolicy) +#pragma alloc_text(PAGE, OsrFxReadFdoRegistryKeyValue) +#pragma alloc_text(PAGE, GetDeviceEventLoggingNames) +#endif + + +/*++ +Routine Description: + + EvtDeviceAdd is called by the framework in response to AddDevice + call from the PnP manager. We create and initialize a Device object to + represent a new instance of the device. All the software resources + should be allocated in this callback. + +Arguments: + + Driver - Handle to a framework driver object created in DriverEntry + + DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +NTSTATUS +OsrFxEvtDeviceAdd( + _In_ WDFDRIVER Driver, + _In_ PWDFDEVICE_INIT DeviceInit + ) +{ + WDF_PNPPOWER_EVENT_CALLBACKS PnpPowerCallbacks; + WDF_OBJECT_ATTRIBUTES Attributes; + NTSTATUS Status; + WDFDEVICE Device; + WDF_DEVICE_PNP_CAPABILITIES PnpCaps; + WDF_IO_QUEUE_CONFIG IoQueueConfig; + PDEVICE_CONTEXT DeviceContext; + WDFQUEUE Queue; + GUID Activity; + + UNREFERENCED_PARAMETER(Driver); + + PAGED_CODE(); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP,"--> OsrFxEvtDeviceAdd routine\n"); + + // + // Initialize the PnpPowerCallbacks structure. Callback events for PNP + // and Power are specified here. If you don't supply any callbacks, + // the Framework will take appropriate default actions based on whether + // DeviceInit is initialized to be an FDO, a PDO or a filter device + // object. + // + WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&PnpPowerCallbacks); + + // + // For usb Devices, PrepareHardware callback is the to place select the + // interface and configure the device. + // + PnpPowerCallbacks.EvtDevicePrepareHardware = OsrFxEvtDevicePrepareHardware; + + // + // These two callbacks start and stop the wdfusb pipe continuous reader + // as we go in and out of the D0-working state. + // + PnpPowerCallbacks.EvtDeviceD0Entry = OsrFxEvtDeviceD0Entry; + PnpPowerCallbacks.EvtDeviceD0Exit = OsrFxEvtDeviceD0Exit; + PnpPowerCallbacks.EvtDeviceSelfManagedIoFlush = OsrFxEvtDeviceSelfManagedIoFlush; + + WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &PnpPowerCallbacks); + + WdfDeviceInitSetIoType(DeviceInit, WdfDeviceIoBuffered); + + // + // Now specify the size of the device extension where we track per-device + // context. DeviceInit is completely initialized. So, call the framework + // to create the device and attach it to the lower stack. + // + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&Attributes, DEVICE_CONTEXT); + + Status = WdfDeviceCreate(&DeviceInit, &Attributes, &Device); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfDeviceCreate failed with Status code %!STATUS!\n", Status); + return Status; + } + + // + // Setup the Activity ID so that we can log events using it. + // + Activity = DeviceToActivityId(Device); + + // + // Get the DeviceObject context by using accessor function specified in + // the WDF_DECLARE_CONTEXT_TYPE_WITH_NAME macro for DEVICE_CONTEXT. + // + DeviceContext = GetDeviceContext(Device); + + // + // Get the device's friendly name and location so that we can use it in + // error logging. If this fails then it will setup dummy strings. + // + GetDeviceEventLoggingNames(Device); + + // + // Tell the framework to set the SurpriseRemovalOK in the DeviceCaps so + // that you don't get the popup in user-mode when you surprise remove the device. + // + WDF_DEVICE_PNP_CAPABILITIES_INIT(&PnpCaps); + PnpCaps.SurpriseRemovalOK = WdfTrue; + + WdfDeviceSetPnpCapabilities(Device, &PnpCaps); + + // + // Create a parallel default queue and register an event callback to + // receive ioctl requests. We will create separate Queues for + // handling read and write requests. All other requests will be + // completed with error Status automatically by the framework. + // + WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&IoQueueConfig, + WdfIoQueueDispatchParallel); + + IoQueueConfig.EvtIoDeviceControl = OsrFxEvtIoDeviceControl; + + // + // By default, Static Driver Verifier (SDV) displays a warning if it + // doesn't find the EvtIoStop callback on a power-managed queue. + // The 'assume' below causes SDV to suppress this warning. If the driver + // has not explicitly set PowerManaged to WdfFalse, the framework creates + // power-managed queues when the device is not a filter driver. Normally + // the EvtIoStop is required for power-managed queues, but for this driver + // it is not needed b/c the driver doesn't hold on to the requests for a + // long time or forward them to other drivers. + // + // If the EvtIoStop callback is not implemented, the framework waits for + // all driver-owned requests to be done before moving into the Dx/sleep + // states or before removing the device, which is the correct behavior + // for this type of driver. If the requests were taking an indeterminate + // amount of time to complete, or if the driver forwarded the requests + // to a lower driver/another stack, the queue should have an + // EvtIoStop/EvtIoResume. + // + __analysis_assume(IoQueueConfig.EvtIoStop != 0); + + Status = WdfIoQueueCreate(Device, + &IoQueueConfig, + WDF_NO_OBJECT_ATTRIBUTES, + &Queue); + + __analysis_assume(IoQueueConfig.EvtIoStop == 0); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfIoQueueCreate failed %!STATUS!\n", Status); + goto Error; + } + + // + // We will create a separate sequential queue and configure it + // to receive read requests. We also need to register a EvtIoStop + // handler so that we can acknowledge requests that are pending + // at the target driver. + // + WDF_IO_QUEUE_CONFIG_INIT(&IoQueueConfig, WdfIoQueueDispatchSequential); + + IoQueueConfig.EvtIoRead = OsrFxEvtIoRead; + IoQueueConfig.EvtIoStop = OsrFxEvtIoStop; + + Status = WdfIoQueueCreate(Device, + &IoQueueConfig, + WDF_NO_OBJECT_ATTRIBUTES, + &Queue); + + if (!NT_SUCCESS (Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfIoQueueCreate failed 0x%x\n", Status); + goto Error; + } + + Status = WdfDeviceConfigureRequestDispatching(Device, + Queue, + WdfRequestTypeRead); + + if (!NT_SUCCESS (Status)) + { + assert(NT_SUCCESS(Status)); + + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfDeviceConfigureRequestDispatching failed 0x%x\n", Status); + goto Error; + } + + + // + // We will create another sequential queue and configure it + // to receive write requests. + // + WDF_IO_QUEUE_CONFIG_INIT(&IoQueueConfig, WdfIoQueueDispatchSequential); + + IoQueueConfig.EvtIoWrite = OsrFxEvtIoWrite; + IoQueueConfig.EvtIoStop = OsrFxEvtIoStop; + + Status = WdfIoQueueCreate(Device, + &IoQueueConfig, + WDF_NO_OBJECT_ATTRIBUTES, + &Queue); + + if (!NT_SUCCESS (Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfIoQueueCreate failed 0x%x\n", Status); + goto Error; + } + + Status = WdfDeviceConfigureRequestDispatching(Device, + Queue, + WdfRequestTypeWrite); + + if (!NT_SUCCESS (Status)) + { + assert(NT_SUCCESS(Status)); + + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfDeviceConfigureRequestDispatching failed 0x%x\n", Status); + goto Error; + } + + // + // Register a manual I/O queue for handling Interrupt Message Read Requests. + // This queue will be used for storing requests that need to wait for an + // interrupt to occur before they can be completed. + // + WDF_IO_QUEUE_CONFIG_INIT(&IoQueueConfig, WdfIoQueueDispatchManual); + + // + // This queue is used for requests that don't directly access the device. The + // requests in this queue are serviced only when the device is in a fully + // powered state and sends an interrupt. So we can use a non-power managed + // queue to park the requests since we dont care whether the device is idle + // or fully powered up. + // + IoQueueConfig.PowerManaged = WdfFalse; + + Status = WdfIoQueueCreate(Device, + &IoQueueConfig, + WDF_NO_OBJECT_ATTRIBUTES, + &DeviceContext->InterruptMsgQueue); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfIoQueueCreate failed 0x%x\n", Status); + goto Error; + } + + // + // Register a device interface so that app can find our device and talk to it. + // + Status = WdfDeviceCreateDeviceInterface(Device, + (LPGUID) &GUID_DEVINTERFACE_OSRUSBFX2, + NULL // Reference string + ); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfDeviceCreateDeviceInterface failed %!STATUS!\n", Status); + goto Error; + } + +#if defined(NTDDI_WIN10_RS2) && (NTDDI_VERSION >= NTDDI_WIN10_RS2) + // + // Adding Custom Capability: + // + // Adds a custom capability to the device interface instance that allows a Windows + // Store device app to access this interface using Windows.Devices.Custom namespace. + // This capability can be defined either in the INF or here as shown below. In order + // to define it from the INF, uncomment the section "OsrUsb Interface installation" + // from the INF and then remove the block of code below. + // + WDF_DEVICE_INTERFACE_PROPERTY_DATA PropertyData = { 0 }; + static const wchar_t customCapabilities[] = L"microsoft.hsaTestCustomCapability_q536wpkpf5cy2\0"; + + WDF_DEVICE_INTERFACE_PROPERTY_DATA_INIT(&PropertyData, + &GUID_DEVINTERFACE_OSRUSBFX2, + &DEVPKEY_DeviceInterface_UnrestrictedAppCapabilities); + + Status = WdfDeviceAssignInterfaceProperty(Device, + &PropertyData, + DEVPROP_TYPE_STRING_LIST, + sizeof(customCapabilities), + (PVOID)customCapabilities); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfDeviceAssignInterfaceProperty failed %!STATUS!\n", Status); + goto Error; + } +#endif + + // + // Create the lock that we use to serialize calls to ResetDevice(). As an + // alternative to using a WDFWAITLOCK to serialize the calls, a sequential + // WDFQUEUE can be created and reset IOCTLs would be forwarded to it. + // + WDF_OBJECT_ATTRIBUTES_INIT(&Attributes); + Attributes.ParentObject = Device; + + Status = WdfWaitLockCreate(&Attributes, &DeviceContext->ResetDeviceWaitLock); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfWaitLockCreate failed %!STATUS!\n", Status); + goto Error; + } + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- OsrFxEvtDeviceAdd\n"); + + return Status; + +Error: + + // + // Log failure to add the device. + // + EventWriteFailAddDevice(DeviceContext->DeviceName, + DeviceContext->Location, + Status); + + return Status; +} + + +/*++ + +Routine Description: + + In this callback, the driver does whatever is necessary to make the + hardware ready to use. In the case of a USB device, this involves + reading and selecting descriptors. + +Arguments: + + Device - Handle to the device + + ResourceList - Handle to a resource-list object that identifies the + raw hardware resources that the PnP manager assigned + to the Device + + ResourceListTranslated - Handle to a resource-list object that + identifies the translated hardware resources + that the PnP manager assigned to the device + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +NTSTATUS +OsrFxEvtDevicePrepareHardware( + _In_ WDFDEVICE Device, + _In_ WDFCMRESLIST ResourceList, + _In_ WDFCMRESLIST ResourceListTranslated + ) +{ + NTSTATUS Status; + PDEVICE_CONTEXT DeviceContext; + WDF_USB_DEVICE_INFORMATION DeviceInfo; + ULONG WaitWakeEnable; + + UNREFERENCED_PARAMETER(ResourceList); + UNREFERENCED_PARAMETER(ResourceListTranslated); + + WaitWakeEnable = FALSE; + + PAGED_CODE(); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, + "--> EvtDevicePrepareHardware\n"); + + DeviceContext = GetDeviceContext(Device); + + // + // Create a USB device handle so that we can communicate with the + // underlying USB stack. The WDFUSBDEVICE handle is used to query, + // configure, and manage all aspects of the USB device. + // These aspects include device properties, bus properties, + // and I/O creation and synchronization. We only create the device the + // first time that PrepareHardware is called. If the device is restarted by + // PnP Manager to rebalance resources, we will use the same device handle + // but then select the interfaces again because the USB stack could + // reconfigure the device on restart. + // + if (DeviceContext->UsbDevice == NULL) + { + Status = WdfUsbTargetDeviceCreate(Device, + WDF_NO_OBJECT_ATTRIBUTES, + &DeviceContext->UsbDevice); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfUsbTargetDeviceCreate failed with status code %!STATUS!\n", Status); + return Status; + } + } + + // + // Retrieve USBD version information, port driver capabilites and device + // capabilites such as speed, power, etc. + // + WDF_USB_DEVICE_INFORMATION_INIT(&DeviceInfo); + + Status = WdfUsbTargetDeviceRetrieveInformation(DeviceContext->UsbDevice, + &DeviceInfo); + if (NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, + "IsDeviceHighSpeed: %s\n", + (DeviceInfo.Traits & WDF_USB_DEVICE_TRAIT_AT_HIGH_SPEED) ? "TRUE" : + "FALSE"); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, + "IsDeviceSelfPowered: %s\n", + (DeviceInfo.Traits & WDF_USB_DEVICE_TRAIT_SELF_POWERED) ? "TRUE" : + "FALSE"); + + WaitWakeEnable = DeviceInfo.Traits & + WDF_USB_DEVICE_TRAIT_REMOTE_WAKE_CAPABLE; + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, + "IsDeviceRemoteWakeable: %s\n", + WaitWakeEnable ? "TRUE" : + "FALSE"); + // + // Save these for use later. + // + DeviceContext->UsbDeviceTraits = DeviceInfo.Traits; + } + else + { + DeviceContext->UsbDeviceTraits = 0; + } + + Status = SelectInterfaces(Device); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "SelectInterfaces failed 0x%x\n", Status); + + return Status; + } + + // + // Enable wait-wake and idle timeout if the device supports it. + // + if (WaitWakeEnable) + { + Status = OsrFxSetPowerPolicy(Device); + + if (!NT_SUCCESS (Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "OsrFxSetPowerPolicy failed %!STATUS!\n", Status); + return Status; + } + } + + Status = OsrFxConfigContReaderForInterruptEndPoint(DeviceContext); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- EvtDevicePrepareHardware\n"); + + return Status; +} + + +/*++ + +Routine Description: + + EvtDeviceD0Entry event callback must perform any operations that are + necessary before the specified device is used. It will be called every + time the hardware needs to be (re-)initialized. + + This function is not marked pageable because this function is in the + device power-up path. When a function is marked pagable and the code + section is paged out, it will generate a page fault which could impact + the fast resume behavior because the client driver will have to wait + until the system drivers can service this page fault. + + This function runs at PASSIVE_LEVEL, even though it is not paged. A + driver can optionally make this function pageable if DO_POWER_PAGABLE + is set. Even if DO_POWER_PAGABLE isn't set, this function still runs + at PASSIVE_LEVEL. In this case, though, the function absolutely must + not do anything that will cause a page fault. + +Arguments: + + Device - Handle to a framework device object + + PreviousState - Device power state which the device was in most recently. + If the device is being newly started, this will be + PowerDeviceUnspecified. + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +NTSTATUS +OsrFxEvtDeviceD0Entry( + _In_ WDFDEVICE Device, + _In_ WDF_POWER_DEVICE_STATE PreviousState + ) +{ + PDEVICE_CONTEXT DeviceContext; + NTSTATUS Status; + BOOLEAN IsTargetStarted; + + DeviceContext = GetDeviceContext(Device); + IsTargetStarted = FALSE; + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_POWER, + "-->OsrFxEvtEvtDeviceD0Entry - coming from %s\n", + DbgDevicePowerString(PreviousState)); + + // + // Since continuous reader is configured for this interrupt-pipe, we must explicitly start + // the I/O target to get the framework to post read requests. + // + Status = WdfIoTargetStart(WdfUsbTargetPipeGetIoTarget(DeviceContext->InterruptPipe)); + + if (!NT_SUCCESS(Status)) { + TraceEvents(TRACE_LEVEL_ERROR, DBG_POWER, + "Failed to start interrupt pipe %!STATUS!\n", Status); + goto End; + } + + IsTargetStarted = TRUE; + +End: + + if (!NT_SUCCESS(Status)) + { + // + // Failure in D0Entry will lead to the device being removed. So stop + // sthe continuous reader in preparation for the ensuing remove. + // + if (IsTargetStarted) + { + WdfIoTargetStop(WdfUsbTargetPipeGetIoTarget(DeviceContext->InterruptPipe), + WdfIoTargetCancelSentIo); + } + } + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_POWER, "<--OsrFxEvtEvtDeviceD0Entry\n"); + + return Status; +} + + +/*++ + +Routine Description: + + This routine undoes anything done in EvtDeviceD0Entry. It is called + whenever the device leaves the D0 state, which happens when the device is + stopped, when it is removed, and when it is powered off. + + The device is still in D0 when this callback is invoked, which means that + the driver can still touch hardware in this routine. + + EvtDeviceD0Exit event callback must perform any operations that are + necessary before the specified device is moved out of the D0 state. If the + driver needs to save hardware state before the device is powered down, then + that should be done here. + + This function runs at PASSIVE_LEVEL, though it is generally not paged. A + driver can optionally make this function pageable if DO_POWER_PAGABLE is set. + + Even if DO_POWER_PAGABLE isn't set, this function still runs at + PASSIVE_LEVEL. In this case, though, the function absolutely must not do + anything that will cause a page fault. + +Arguments: + + Device - Handle to a framework device object + + TargetState - Device power state which the device will be put in once this + callback is complete + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + + If this function succeeds it implies that the device can be used. + +--*/ +NTSTATUS +OsrFxEvtDeviceD0Exit( + _In_ WDFDEVICE Device, + _In_ WDF_POWER_DEVICE_STATE TargetState + ) +{ + PDEVICE_CONTEXT DeviceContext; + + PAGED_CODE(); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_POWER, + "-->OsrFxEvtDeviceD0Exit - moving to %s\n", + DbgDevicePowerString(TargetState)); + + DeviceContext = GetDeviceContext(Device); + + WdfIoTargetStop(WdfUsbTargetPipeGetIoTarget(DeviceContext->InterruptPipe), WdfIoTargetCancelSentIo); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_POWER, + "<--OsrFxEvtDeviceD0Exit\n"); + + return STATUS_SUCCESS; +} + + +/*++ + +Routine Description: + + This routine handles flush Activity for the device's + self-managed I/O operations. + +Arguments: + + Device - Handle to a framework device object + +Return Value: + + VOID + +--*/ +VOID +OsrFxEvtDeviceSelfManagedIoFlush( + _In_ WDFDEVICE Device + ) +{ + // + // Service the interrupt message queue to drain any outstanding + // requests + // + OsrUsbIoctlGetInterruptMessage(Device, STATUS_DEVICE_REMOVED); +} + + +/*++ + +Routine Description: + + This routine sets the power policy for the device. + +Arguments: + + Device - Handle to a framework device object + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +OsrFxSetPowerPolicy( + _In_ WDFDEVICE Device + ) +{ + WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS idleSettings; + WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS wakeSettings; + NTSTATUS Status = STATUS_SUCCESS; + + PAGED_CODE(); + + // + // Init the idle policy structure. + // + WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT(&idleSettings, IdleUsbSelectiveSuspend); + + idleSettings.IdleTimeout = 10000; // 10 seconds + + Status = WdfDeviceAssignS0IdleSettings(Device, &idleSettings); + + if ( !NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfDeviceSetPowerPolicyS0IdlePolicy failed %x\n", Status); + return Status; + } + + // + // Init wait-wake policy structure. + // + WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS_INIT(&wakeSettings); + + Status = WdfDeviceAssignSxWakeSettings(Device, &wakeSettings); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfDeviceAssignSxWakeSettings failed %x\n", Status); + return Status; + } + + return Status; +} + + +/*++ + +Routine Description: + + This helper routine selects the configuration, interface and + creates a context for every pipe (end point) in that interface. + +Arguments: + + Device - Handle to a framework device object + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +SelectInterfaces( + _In_ WDFDEVICE Device + ) +{ + WDF_USB_DEVICE_SELECT_CONFIG_PARAMS configParams; + NTSTATUS Status = STATUS_SUCCESS; + PDEVICE_CONTEXT DeviceContext; + WDFUSBPIPE Pipe; + WDF_USB_PIPE_INFORMATION PipeInfo; + UCHAR Index; + UCHAR NumberConfiguredPipes; + WDFUSBINTERFACE UsbInterface; + + PAGED_CODE(); + + DeviceContext = GetDeviceContext(Device); + + WDF_USB_DEVICE_SELECT_CONFIG_PARAMS_INIT_SINGLE_INTERFACE( &configParams); + + UsbInterface = WdfUsbTargetDeviceGetInterface(DeviceContext->UsbDevice, 0); + + if (NULL == UsbInterface) + { + Status = STATUS_UNSUCCESSFUL; + + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "WdfUsbTargetDeviceGetInterface 0 failed %!STATUS! \n", + Status); + return Status; + } + + configParams.Types.SingleInterface.ConfiguredUsbInterface = UsbInterface; + + configParams.Types.SingleInterface.NumberConfiguredPipes = WdfUsbInterfaceGetNumConfiguredPipes(UsbInterface); + + DeviceContext->UsbInterface = configParams.Types.SingleInterface.ConfiguredUsbInterface; + + NumberConfiguredPipes = configParams.Types.SingleInterface.NumberConfiguredPipes; + + // + // Get pipe handles. + // + for (Index = 0; Index < NumberConfiguredPipes; Index++) + { + WDF_USB_PIPE_INFORMATION_INIT(&PipeInfo); + + Pipe = WdfUsbInterfaceGetConfiguredPipe(DeviceContext->UsbInterface, + Index, + &PipeInfo); + + // + // Tell the framework that it's okay to read less than + // MaximumPacketSize. + // + WdfUsbTargetPipeSetNoMaximumPacketSizeCheck(Pipe); + + if (WdfUsbPipeTypeInterrupt == PipeInfo.PipeType) + { + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, + "Interrupt Pipe is 0x%p\n", Pipe); + DeviceContext->InterruptPipe = Pipe; + } + + if ((WdfUsbPipeTypeBulk == PipeInfo.PipeType) && + (WdfUsbTargetPipeIsInEndpoint(Pipe))) + { + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, + "BulkInput Pipe is 0x%p\n", Pipe); + DeviceContext->BulkReadPipe = Pipe; + } + + if ((WdfUsbPipeTypeBulk == PipeInfo.PipeType) && + (WdfUsbTargetPipeIsOutEndpoint(Pipe))) + { + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, + "BulkOutput Pipe is 0x%p\n", Pipe); + DeviceContext->BulkWritePipe = Pipe; + } + + } + + // + // If we didn't find all 3 pipes, fail the start. + // + if (!((DeviceContext->BulkWritePipe) && + ((DeviceContext->BulkReadPipe) && + (DeviceContext->InterruptPipe)))) + { + Status = STATUS_INVALID_DEVICE_STATE; + + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, + "Device is not configured properly %!STATUS!\n", + Status); + + return Status; + } + + return Status; +} + + +/*++ + +Routine Description: + + Retrieve the friendly name and the location string into WDFMEMORY objects + and store them in the device context. + +Arguments: + + Device - Handle to a device framework object + +Return Value: + + VOID + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +VOID +GetDeviceEventLoggingNames( + _In_ WDFDEVICE Device + ) +{ + PDEVICE_CONTEXT DeviceContext = GetDeviceContext(Device); + WDF_OBJECT_ATTRIBUTES ObjectAttributes; + WDFMEMORY DeviceNameMemory = NULL; + WDFMEMORY LocationMemory = NULL; + NTSTATUS Status; + + PAGED_CODE(); + + // + // We want both memory objects to be children of the device so that they + // will be deleted automatically when the device is removed. + // + WDF_OBJECT_ATTRIBUTES_INIT(&ObjectAttributes); + ObjectAttributes.ParentObject = Device; + + // + // First get the length of the string. If the FriendlyName + // is not there then get the length of the device's description. + // + Status = WdfDeviceAllocAndQueryProperty(Device, + DevicePropertyFriendlyName, + NonPagedPoolNx, + &ObjectAttributes, + &DeviceNameMemory); + + if (!NT_SUCCESS(Status)) + { + Status = WdfDeviceAllocAndQueryProperty(Device, + DevicePropertyDeviceDescription, + NonPagedPoolNx, + &ObjectAttributes, + &DeviceNameMemory); + } + + if (NT_SUCCESS(Status)) + { + DeviceContext->DeviceNameMemory = DeviceNameMemory; + DeviceContext->DeviceName = WdfMemoryGetBuffer(DeviceNameMemory, NULL); + } + else + { + DeviceContext->DeviceNameMemory = NULL; + DeviceContext->DeviceName = L"(error retrieving name)"; + } + + // + // Retrieve the device location string. + // + Status = WdfDeviceAllocAndQueryProperty(Device, + DevicePropertyLocationInformation, + NonPagedPoolNx, + WDF_NO_OBJECT_ATTRIBUTES, + &LocationMemory); + + if (NT_SUCCESS(Status)) + { + DeviceContext->LocationMemory = LocationMemory; + DeviceContext->Location = WdfMemoryGetBuffer(LocationMemory, NULL); + } + else + { + DeviceContext->LocationMemory = NULL; + DeviceContext->Location = L"(error retrieving location)"; + } +} + + +/*++ + +Routine Description: + + Retrieve the correct string for a given power device state. + +Arguments: + + Type - The device power state to turn into a string + +Return Value: + + The name that corresponds to the WDF_POWER_DEVICE_STATE given, or + "Unknown Device Power State" if none was found. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +PCHAR +DbgDevicePowerString( + _In_ WDF_POWER_DEVICE_STATE Type + ) +{ + switch (Type) + { + case WdfPowerDeviceInvalid: + return "WdfPowerDeviceInvalid"; + case WdfPowerDeviceD0: + return "WdfPowerDeviceD0"; + case WdfPowerDeviceD1: + return "WdfPowerDeviceD1"; + case WdfPowerDeviceD2: + return "WdfPowerDeviceD2"; + case WdfPowerDeviceD3: + return "WdfPowerDeviceD3"; + case WdfPowerDeviceD3Final: + return "WdfPowerDeviceD3Final"; + case WdfPowerDevicePrepareForHibernation: + return "WdfPowerDevicePrepareForHibernation"; + case WdfPowerDeviceMaximum: + return "WdfPowerDeviceMaximum"; + default: + return "Unknown Device Power State"; + } +}
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/driver.c b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/driver.c new file mode 100644 index 00000000..2be5d2ed --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/driver.c @@ -0,0 +1,281 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + Driver.c + +Abstract: + + Main module. + + This driver is for the Open System Resources USB-FX2 Learning Kit designed + and built by OSR specifically for use in teaching software developers how to write + drivers for USB devices. + + The board supports a single configuration. The board automatically + detects the speed of the host controller, and supplies either the + high or full speed configuration based on the host controller's speed. + + The firmware supports 3 endpoints: + + Endpoint number 1 is used to indicate the state of the 8-switch + switch-pack on the OSR USB-FX2 board. A single byte representing + the switch state is sent (a) when the board is first started, + (b) when the board resumes after selective-suspend, + (c) whenever the state of the switches is changed. + + Endpoints 6 and 8 perform an internal loop-back function. + Data that is sent to the board at EP6 is returned to the host on EP8. + + For further information on the endpoints, please refer to the spec + http://www.osronline.com/hardware/OSRFX2_32.pdf. + + Vendor ID of the device is 0x4705 and Product ID is 0x210. + +Environment: + + User mode only + +--*/ + +#include "osrusbfx2.h" + +#if defined(EVENT_TRACING) +// +// The trace message header (.tmh) file must be included in a source file +// before any WPP macro calls and after defining a WPP_CONTROL_GUIDS +// macro (defined in trace.h). During the compilation, WPP scans the source +// files for DoTraceMessage() calls and builds a .tmh file which stores a unique +// data GUID for each message, the text resource string for each message, +// and the data types of the variables passed in for each message. This file +// is automatically generated and used during post-processing. +// +#include "driver.tmh" +#else +ULONG DebugLevel = TRACE_LEVEL_INFORMATION; +ULONG DebugFlag = 0xff; +#endif + +#ifdef ALLOC_PRAGMA +#pragma alloc_text(INIT, DriverEntry) +#pragma alloc_text(PAGE, OsrFxEvtDriverContextCleanup) +#endif + + +/*++ + +Routine Description: + + DriverEntry initializes the driver and is the first routine called by the + system after the driver is loaded. + +Parameters Description: + + DriverObject - Represents the instance of the function driver that is loaded + into memory. DriverEntry must initialize members of + DriverObject before it returns to the caller. DriverObject + is allocated by the system before the driver is loaded, and + it is released by the system after the system unloads the + function driver from memory + + RegistryPath - Represents the driver specific path in the registry. + The function driver can use the path to store driver related + data between reboots. The path does not store hardware + instance specific data + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +NTSTATUS +DriverEntry( + _In_ PDRIVER_OBJECT DriverObject, + _In_ PUNICODE_STRING RegistryPath + ) +{ + WDF_DRIVER_CONFIG Config; + NTSTATUS Status; + WDF_OBJECT_ATTRIBUTES Attributes; + + // + // Initialize WPP Tracing. + // + WPP_INIT_TRACING(DriverObject, RegistryPath); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, + "OSRUSBFX2 Driver Sample - Driver Framework Edition.\n"); + + // + // Register with ETW (unified tracing). + // + EventRegisterOSRUSBFX2(); + + // + // Initiialize driver config to control the attributes that + // are global to the driver. Note that framework by default + // provides a driver unload routine. If you create any resources + // in the DriverEntry and want to be cleaned in driver unload, + // you can override that by manually setting the EvtDriverUnload in the + // config structure. In general xxx_CONFIG_INIT macros are provided to + // initialize most commonly used members. + // + + WDF_DRIVER_CONFIG_INIT(&Config, + OsrFxEvtDeviceAdd); + + // + // Register a cleanup callback so that we can call WPP_CLEANUP when + // the framework driver object is deleted during driver unload. + // + WDF_OBJECT_ATTRIBUTES_INIT(&Attributes); + Attributes.EvtCleanupCallback = OsrFxEvtDriverContextCleanup; + + // + // Create a framework driver object to represent our driver. + // + Status = WdfDriverCreate(DriverObject, + RegistryPath, + &Attributes, + &Config, + WDF_NO_HANDLE); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, + "WdfDriverCreate failed with Status 0x%x\n", Status); + // + // Cleanup tracing here because DriverContextCleanup will not be called + // as we have failed to create WDFDRIVER object itself. + // Please note that if your return failure from DriverEntry after the + // WDFDRIVER object is created successfully, you don't have to + // call WPP cleanup because in those cases DriverContextCleanup + // will be executed when the framework deletes the DriverObject. + // + WPP_CLEANUP(DriverObject); + EventUnregisterOSRUSBFX2(); + } + + return Status; +} + + +/*++ +Routine Description: + + Free resources allocated in DriverEntry that are not automatically + cleaned up by the framework. + +Arguments: + + Driver - Handle to a WDF driver object + +Return Value: + + VOID + +--*/ +VOID +OsrFxEvtDriverContextCleanup( + _In_ WDFOBJECT Driver + ) +{ + PAGED_CODE (); + + // + // For the case when WPP is not being used. + // + UNREFERENCED_PARAMETER(Driver); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, + "--> OsrFxEvtDriverContextCleanup\n"); + + WPP_CLEANUP(WdfDriverWdmGetDriverObject((WDFDRIVER) Driver)); + + EventUnregisterOSRUSBFX2(); +} + + +#if !defined(EVENT_TRACING) +/*++ + +Routine Description: + + Debug print for the sample driver. + +Arguments: + + DebugPrintLevel - Print level between 0 and 3, with 3 the most verbose + + DebugPrintFlag - Message mask + + DebugMessage - Format string of the message to print + + ... - Values used by the format string + +Return Value: + + VOID + + --*/ +VOID +TraceEvents ( + _In_ ULONG DebugPrintLevel, + _In_ ULONG DebugPrintFlag, + _Printf_format_string_ _In_ PCSTR DebugMessage, + ... + ) +{ +#if DBG +#define TEMP_BUFFER_SIZE 1024 + va_list List; + CHAR DebugMessageBuffer[TEMP_BUFFER_SIZE]; + HRESULT hr; + + va_start(List, DebugMessage); + + if (DebugMessage) + { + // + // Using new safe string functions instead of _vsnprintf. + // This function takes care of NULL terminating if the message + // is longer than the buffer. + // + hr = StringCchVPrintfA(DebugMessageBuffer, + sizeof(DebugMessageBuffer), + DebugMessage, + List); + + if(FAILED(hr)) + { + DbgPrint(_DRIVER_NAME_": StringCchVPrintfA failed with HRESULT 0x%x\n", hr); + return; + } + + if ((DebugPrintLevel <= TRACE_LEVEL_ERROR) || + ((DebugPrintLevel <= DebugLevel) && + ((DebugPrintFlag & DebugFlag) == DebugPrintFlag))) + { + DbgPrint("%s %s", _DRIVER_NAME_, DebugMessageBuffer); + } + } + + va_end(List); + + return; +#else + UNREFERENCED_PARAMETER(DebugPrintLevel); + UNREFERENCED_PARAMETER(DebugPrintFlag); + UNREFERENCED_PARAMETER(DebugMessage); +#endif +} + +#endif
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/ioctl.c b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/ioctl.c new file mode 100644 index 00000000..2c6792a4 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/ioctl.c @@ -0,0 +1,1151 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + Ioctl.c + +Abstract: + + USB device driver for OSR USB-FX2 Learning Kit + +Environment: + + User mode only + +--*/ + +#include "osrusbfx2.h" + +#if defined(EVENT_TRACING) +#include "ioctl.tmh" +#endif + +#pragma alloc_text(PAGE, OsrFxEvtIoDeviceControl) +#pragma alloc_text(PAGE, ResetPipe) +#pragma alloc_text(PAGE, ResetDevice) +#pragma alloc_text(PAGE, ReenumerateDevice) +#pragma alloc_text(PAGE, GetBarGraphState) +#pragma alloc_text(PAGE, SetBarGraphState) +#pragma alloc_text(PAGE, GetSevenSegmentState) +#pragma alloc_text(PAGE, SetSevenSegmentState) +#pragma alloc_text(PAGE, GetSwitchState) + + +/*++ + +Routine Description: + + This event is called when the framework receives IRP_MJ_DEVICE_CONTROL + requests from the system. + +Arguments: + + Queue - Handle to the framework queue object that is + associated with the I/O request + + Request - Handle to a framework request object + + OutputBufferLength - Length of the request's output buffer, if an output + buffer is available + + InputBufferLength - Length of the request's input buffer, if an input + buffer is available + + IoControlCode - The driver-defined or system-defined I/O control code + (IOCTL) that is associated with the request + +Return Value: + + VOID + +--*/ +VOID +OsrFxEvtIoDeviceControl( + _In_ WDFQUEUE Queue, + _In_ WDFREQUEST Request, + _In_ size_t OutputBufferLength, + _In_ size_t InputBufferLength, + _In_ ULONG IoControlCode + ) +{ + WDFDEVICE Device; + PDEVICE_CONTEXT DeviceContext; + size_t BytesReturned = 0; + PBAR_GRAPH_STATE BarGraphState = NULL; + PSWITCH_STATE SwitchState = NULL; + PUCHAR SevenSegment = NULL; + BOOLEAN RequestPending = FALSE; + NTSTATUS Status = STATUS_INVALID_DEVICE_REQUEST; + + UNREFERENCED_PARAMETER(InputBufferLength); + UNREFERENCED_PARAMETER(OutputBufferLength); + + PAGED_CODE(); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, + "--> OsrFxEvtIoDeviceControl\n"); + + // + // Initialize variables. + // + Device = WdfIoQueueGetDevice(Queue); + DeviceContext = GetDeviceContext(Device); + + switch(IoControlCode) + { + + case IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR: + { + PUSB_CONFIGURATION_DESCRIPTOR ConfigurationDescriptor = NULL; + USHORT RequiredSize = 0; + + // + // First get the size of the config descriptor. + // + Status = WdfUsbTargetDeviceRetrieveConfigDescriptor(DeviceContext->UsbDevice, + NULL, + &RequiredSize); + + if (Status != STATUS_BUFFER_TOO_SMALL) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "WdfUsbTargetDeviceRetrieveConfigDescriptor failed 0x%x\n", + Status); + break; + } + + // + // Get the buffer - make sure the buffer is big enough. + // + Status = WdfRequestRetrieveOutputBuffer(Request, + (size_t)RequiredSize, + &ConfigurationDescriptor, + NULL); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "WdfRequestRetrieveOutputBuffer failed 0x%x\n", + Status); + break; + } + + Status = WdfUsbTargetDeviceRetrieveConfigDescriptor(DeviceContext->UsbDevice, + ConfigurationDescriptor, + &RequiredSize); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "WdfUsbTargetDeviceRetrieveConfigDescriptor failed 0x%x\n", + Status); + break; + } + + BytesReturned = RequiredSize; + } + + break; + + case IOCTL_OSRUSBFX2_RESET_DEVICE: + + Status = ResetDevice(Device); + break; + + case IOCTL_OSRUSBFX2_REENUMERATE_DEVICE: + // + // Otherwise, call our function to re-enumerate the device. + // + Status = ReenumerateDevice(DeviceContext); + + BytesReturned = 0; + break; + + case IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY: + // + // Make sure the caller's output buffer is large enough + // to hold the state of the bar graph. + // + Status = WdfRequestRetrieveOutputBuffer(Request, + sizeof(BAR_GRAPH_STATE), + &BarGraphState, + NULL); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "User's output buffer is too small for this IOCTL, expecting a BAR_GRAPH_STATE\n"); + break; + } + + // + // Call our function to get the bar graph state. + // + Status = GetBarGraphState(DeviceContext, BarGraphState); + + // + // Return the user their data. + // + if (NT_SUCCESS(Status)) + { + BytesReturned = sizeof(BAR_GRAPH_STATE); + } + else + { + BytesReturned = 0; + } + + break; + + case IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY: + Status = WdfRequestRetrieveInputBuffer(Request, + sizeof(BAR_GRAPH_STATE), + &BarGraphState, + NULL); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "User's input buffer is too small for this IOCTL, expecting a BAR_GRAPH_STATE\n"); + break; + } + + // + // Call our routine to set the bar graph state. + // + Status = SetBarGraphState(DeviceContext, BarGraphState); + + // + // There's no data returned for this call. + // + BytesReturned = 0; + break; + + case IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY: + Status = WdfRequestRetrieveOutputBuffer(Request, + sizeof(UCHAR), + &SevenSegment, + NULL); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "User's output buffer is too small for this IOCTL, expecting an UCHAR\n"); + break; + } + + // + // Call our function to get the 7 segment state. + // + Status = GetSevenSegmentState(DeviceContext, SevenSegment); + + // + // If we succeeded return the user their data. + // + if (NT_SUCCESS(Status)) + { + BytesReturned = sizeof(UCHAR); + } + else + { + BytesReturned = 0; + } + + break; + + case IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY: + Status = WdfRequestRetrieveInputBuffer(Request, + sizeof(UCHAR), + &SevenSegment, + NULL); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "User's input buffer is too small for this IOCTL, expecting an UCHAR\n"); + + BytesReturned = sizeof(UCHAR); + break; + } + + // + // Call our routine to set the 7 segment state. + // + Status = SetSevenSegmentState(DeviceContext, SevenSegment); + + // + // There's no data returned for this call. + // + BytesReturned = 0; + break; + + case IOCTL_OSRUSBFX2_READ_SWITCHES: + Status = WdfRequestRetrieveOutputBuffer(Request, + sizeof(SWITCH_STATE), + &SwitchState, + NULL); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "User's output buffer is too small for this IOCTL, expecting a SWITCH_STATE\n"); + + BytesReturned = sizeof(SWITCH_STATE); + break; + } + + // + // Call our routine to get the state of the switches. + // + Status = GetSwitchState(DeviceContext, SwitchState); + + // + // If successful, return the user their data. + // + if (NT_SUCCESS(Status)) + { + BytesReturned = sizeof(SWITCH_STATE); + } + else + { + // + // Don't return any data. + // + BytesReturned = 0; + } + + break; + + case IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE: + // + // Forward the request to an interrupt message queue and dont complete + // the request until an interrupt from the USB Device occurs. + // + Status = WdfRequestForwardToIoQueue(Request, + DeviceContext->InterruptMsgQueue); + + if (NT_SUCCESS(Status)) + { + RequestPending = TRUE; + } + + break; + + default : + Status = STATUS_INVALID_DEVICE_REQUEST; + break; + } + + if (RequestPending == FALSE) + { + WdfRequestCompleteWithInformation(Request, Status, BytesReturned); + } + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, + "<-- OsrFxEvtIoDeviceControl\n"); + + return; +} + + +/*++ + +Routine Description: + + This routine resets the pipe. + +Arguments: + + Pipe - framework pipe handle + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +ResetPipe( + _In_ WDFUSBPIPE Pipe + ) +{ + NTSTATUS Status; + + PAGED_CODE(); + + // + // This routine synchronously submits a URB_FUNCTION_RESET_PIPE + // request down the stack. + // + Status = WdfUsbTargetPipeResetSynchronously(Pipe, + WDF_NO_HANDLE, + NULL); + + if (NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, + "ResetPipe - success\n"); + + Status = STATUS_SUCCESS; + } + else + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "ResetPipe - failed\n"); + } + + return Status; +} + + +/*++ + +Routine Description: + + This routine stops all of the device's pipes. + +Arguments: + + DeviceContext - The device context with the pipe information + +Return Value: + + VOID + +--*/ +VOID +StopAllPipes( + _In_ PDEVICE_CONTEXT DeviceContext + ) +{ + WdfIoTargetStop(WdfUsbTargetPipeGetIoTarget(DeviceContext->InterruptPipe), + WdfIoTargetCancelSentIo); + + WdfIoTargetStop(WdfUsbTargetPipeGetIoTarget(DeviceContext->BulkReadPipe), + WdfIoTargetCancelSentIo); + + WdfIoTargetStop(WdfUsbTargetPipeGetIoTarget(DeviceContext->BulkWritePipe), + WdfIoTargetCancelSentIo); +} + + +/*++ + +Routine Description: + + This routine starts all of the device's pipes. + +Arguments: + + DeviceContext - The device context with the pipe information + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +NTSTATUS +StartAllPipes( + _In_ PDEVICE_CONTEXT DeviceContext + ) +{ + NTSTATUS Status; + + Status = WdfIoTargetStart(WdfUsbTargetPipeGetIoTarget(DeviceContext->InterruptPipe)); + + if (!NT_SUCCESS(Status)) + { + return Status; + } + + Status = WdfIoTargetStart(WdfUsbTargetPipeGetIoTarget(DeviceContext->BulkReadPipe)); + + if (!NT_SUCCESS(Status)) + { + return Status; + } + + Status = WdfIoTargetStart(WdfUsbTargetPipeGetIoTarget(DeviceContext->BulkWritePipe)); + + if (!NT_SUCCESS(Status)) + { + return Status; + } + + return Status; +} + + +/*++ + +Routine Description: + + This routine calls WdfUsbTargetDeviceResetPortSynchronously to reset the + device if it's still connected. + +Arguments: + + Device - Handle to a framework device object + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +ResetDevice( + _In_ WDFDEVICE Device + ) +{ + PDEVICE_CONTEXT DeviceContext; + NTSTATUS Status; + + PAGED_CODE(); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, + "--> ResetDevice\n"); + + DeviceContext = GetDeviceContext(Device); + + // + // A NULL timeout indicates an infinite wake. + // + Status = WdfWaitLockAcquire(DeviceContext->ResetDeviceWaitLock, NULL); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "ResetDevice - could not acquire lock\n"); + + return Status; + } + + StopAllPipes(DeviceContext); + + Status = WdfUsbTargetDeviceResetPortSynchronously(DeviceContext->UsbDevice); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "ResetDevice failed - 0x%x\n", + Status); + } + + Status = StartAllPipes(DeviceContext); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "Failed to start all pipes - 0x%x\n", + Status); + } + + WdfWaitLockRelease(DeviceContext->ResetDeviceWaitLock); + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_IOCTL, + "<-- ResetDevice\n"); + + return Status; +} + + +/*++ + +Routine Description + + This routine re-enumerates the USB device. + +Arguments: + + DeviceContext - One of our device extensions + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +ReenumerateDevice( + _In_ PDEVICE_CONTEXT DeviceContext + ) +{ + NTSTATUS Status; + WDF_USB_CONTROL_SETUP_PACKET ControlSetupPacket; + WDF_REQUEST_SEND_OPTIONS SendOptions; + GUID Activity; + + PAGED_CODE(); + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "--> ReenumerateDevice\n"); + + WDF_REQUEST_SEND_OPTIONS_INIT(&SendOptions, + WDF_REQUEST_SEND_OPTION_TIMEOUT); + + WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT(&SendOptions, + DEFAULT_CONTROL_TRANSFER_TIMEOUT); + + WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&ControlSetupPacket, + BmRequestHostToDevice, + BmRequestToDevice, + USBFX2LK_REENUMERATE, + 0, + 0); + + + Status = WdfUsbTargetDeviceSendControlTransferSynchronously(DeviceContext->UsbDevice, + WDF_NO_HANDLE, + &SendOptions, + &ControlSetupPacket, + NULL, + NULL); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "ReenumerateDevice: Failed to Reenumerate - 0x%x \n", + Status); + } + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "<-- ReenumerateDevice\n"); + + // + // Send event to the event log. + // + Activity = DeviceToActivityId(WdfObjectContextGetObject(DeviceContext)); + + EventWriteDeviceReenumerated(DeviceContext->DeviceName, + DeviceContext->Location, + Status); + + return Status; + +} + + +/*++ + +Routine Description + + This routine gets the state of the bar graph on the board. + +Arguments: + + DeviceContext - One of our device extensions + + BarGraphState - Struct that receives the bar graph's state + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +GetBarGraphState( + _In_ PDEVICE_CONTEXT DeviceContext, + _Out_ PBAR_GRAPH_STATE BarGraphState + ) +{ + NTSTATUS Status; + WDF_USB_CONTROL_SETUP_PACKET ControlSetupPacket; + WDF_REQUEST_SEND_OPTIONS SendOptions; + WDF_MEMORY_DESCRIPTOR MemoryDescriptor; + ULONG BytesTransferred; + + PAGED_CODE(); + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "--> GetBarGraphState\n"); + + WDF_REQUEST_SEND_OPTIONS_INIT(&SendOptions, + WDF_REQUEST_SEND_OPTION_TIMEOUT); + + WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT(&SendOptions, + DEFAULT_CONTROL_TRANSFER_TIMEOUT); + + WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&ControlSetupPacket, + BmRequestDeviceToHost, + BmRequestToDevice, + USBFX2LK_READ_BARGRAPH_DISPLAY, + 0, + 0); + + // + // Set the buffer to 0, the board will OR in everything that is set. + // + BarGraphState->BarsAsUChar = 0; + + + WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&MemoryDescriptor, + BarGraphState, + sizeof(BAR_GRAPH_STATE)); + + Status = WdfUsbTargetDeviceSendControlTransferSynchronously(DeviceContext->UsbDevice, + WDF_NO_HANDLE, + &SendOptions, + &ControlSetupPacket, + &MemoryDescriptor, + &BytesTransferred); + + if(!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "GetBarGraphState: Failed to GetBarGraphState - 0x%x \n", + Status); + } + else + { + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "GetBarGraphState: LED mask is 0x%x\n", + BarGraphState->BarsAsUChar); + } + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "<-- GetBarGraphState\n"); + + return Status; + +} + + +/*++ + +Routine Description + + This routine sets the state of the bar graph on the board. + +Arguments: + + DeviceContext - One of our device extensions + + BarGraphState - Struct that describes the bar graph's desired state + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +SetBarGraphState( + _In_ PDEVICE_CONTEXT DeviceContext, + _In_ PBAR_GRAPH_STATE BarGraphState + ) +{ + NTSTATUS Status; + WDF_USB_CONTROL_SETUP_PACKET ControlSetupPacket; + WDF_REQUEST_SEND_OPTIONS SendOptions; + WDF_MEMORY_DESCRIPTOR MemoryDescriptor; + ULONG BytesTransferred; + + PAGED_CODE(); + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "--> SetBarGraphState\n"); + + WDF_REQUEST_SEND_OPTIONS_INIT(&SendOptions, + WDF_REQUEST_SEND_OPTION_TIMEOUT); + + WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT(&SendOptions, + DEFAULT_CONTROL_TRANSFER_TIMEOUT); + + WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&ControlSetupPacket, + BmRequestHostToDevice, + BmRequestToDevice, + USBFX2LK_SET_BARGRAPH_DISPLAY, + 0, + 0); + + WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&MemoryDescriptor, + BarGraphState, + sizeof(BAR_GRAPH_STATE)); + + Status = WdfUsbTargetDeviceSendControlTransferSynchronously(DeviceContext->UsbDevice, + NULL, + &SendOptions, + &ControlSetupPacket, + &MemoryDescriptor, + &BytesTransferred); + + if(!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "SetBarGraphState: Failed - 0x%x \n", + Status); + } + else + { + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "SetBarGraphState: LED mask is 0x%x\n", + BarGraphState->BarsAsUChar); + } + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "<-- SetBarGraphState\n"); + + return Status; +} + + +/*++ + +Routine Description + + This routine gets the state of the 7 segment display on the board + by sending a synchronous control command. + + NOTE: It's not good practice to send a synchronous request in the + context of the user thread because if the transfer takes a long + time to complete, you end up holding the user thread. + + I'm choosing to do synchronous transfer because a) I know this one + completes immediately and b) for demonstration. + +Arguments: + + DeviceContext - One of our device extensions + + SevenSegment - Receives the state of the 7 segment display + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +GetSevenSegmentState( + _In_ PDEVICE_CONTEXT DeviceContext, + _Out_ PUCHAR SevenSegment + ) +{ + NTSTATUS Status; + WDF_USB_CONTROL_SETUP_PACKET ControlSetupPacket; + WDF_REQUEST_SEND_OPTIONS SendOptions; + WDF_MEMORY_DESCRIPTOR MemoryDescriptor; + ULONG BytesTransferred; + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "GetSetSevenSegmentState: Enter\n"); + + PAGED_CODE(); + + WDF_REQUEST_SEND_OPTIONS_INIT(&SendOptions, + WDF_REQUEST_SEND_OPTION_TIMEOUT); + + WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT(&SendOptions, + DEFAULT_CONTROL_TRANSFER_TIMEOUT); + + WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&ControlSetupPacket, + BmRequestDeviceToHost, + BmRequestToDevice, + USBFX2LK_READ_7SEGMENT_DISPLAY, + 0, + 0); + + // + // Set the buffer to 0, the board will OR in everything that is set. + // + *SevenSegment = 0; + + WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&MemoryDescriptor, + SevenSegment, + sizeof(UCHAR)); + + Status = WdfUsbTargetDeviceSendControlTransferSynchronously(DeviceContext->UsbDevice, + NULL, + &SendOptions, + &ControlSetupPacket, + &MemoryDescriptor, + &BytesTransferred); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "GetSevenSegmentState: Failed to get 7 Segment state - 0x%x \n", + Status); + } + else + { + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "GetSevenSegmentState: 7 Segment mask is 0x%x\n", + *SevenSegment); + } + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "GetSetSevenSegmentState: Exit\n"); + + return Status; +} + + +/*++ + +Routine Description + + This routine sets the state of the 7 segment display on the board. + +Arguments: + + DeviceContext - One of our device extensions + + SevenSegment - Desired state of the 7 segment display + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +SetSevenSegmentState( + _In_ PDEVICE_CONTEXT DeviceContext, + _In_ PUCHAR SevenSegment + ) +{ + NTSTATUS Status; + WDF_USB_CONTROL_SETUP_PACKET ControlSetupPacket; + WDF_REQUEST_SEND_OPTIONS SendOptions; + WDF_MEMORY_DESCRIPTOR MemoryDescriptor; + ULONG BytesTransferred; + + PAGED_CODE(); + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "--> SetSevenSegmentState\n"); + + WDF_REQUEST_SEND_OPTIONS_INIT(&SendOptions, + WDF_REQUEST_SEND_OPTION_TIMEOUT); + + WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT(&SendOptions, + DEFAULT_CONTROL_TRANSFER_TIMEOUT); + + WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&ControlSetupPacket, + BmRequestHostToDevice, + BmRequestToDevice, + USBFX2LK_SET_7SEGMENT_DISPLAY, + 0, + 0); + + WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&MemoryDescriptor, + SevenSegment, + sizeof(UCHAR)); + + Status = WdfUsbTargetDeviceSendControlTransferSynchronously(DeviceContext->UsbDevice, + NULL, + &SendOptions, + &ControlSetupPacket, + &MemoryDescriptor, + &BytesTransferred); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "SetSevenSegmentState: Failed to set 7 Segment state - 0x%x \n", + Status); + } + else + { + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "SetSevenSegmentState: 7 Segment mask is 0x%x\n", + *SevenSegment); + } + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "<-- SetSevenSegmentState\n"); + + return Status; + +} + + +/*++ + +Routine Description + + This routine gets the state of the switches on the board. + +Arguments: + + DeviceContext - One of our device extensions + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL or another NTSTATUS error code otherwise. + +--*/ +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +GetSwitchState( + _In_ PDEVICE_CONTEXT DeviceContext, + _In_ PSWITCH_STATE SwitchState + ) +{ + NTSTATUS Status; + WDF_USB_CONTROL_SETUP_PACKET ControlSetupPacket; + WDF_REQUEST_SEND_OPTIONS SendOptions; + WDF_MEMORY_DESCRIPTOR MemoryDescriptor; + ULONG BytesTransferred; + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "--> GetSwitchState\n"); + + PAGED_CODE(); + + WDF_REQUEST_SEND_OPTIONS_INIT(&SendOptions, + WDF_REQUEST_SEND_OPTION_TIMEOUT); + + WDF_REQUEST_SEND_OPTIONS_SET_TIMEOUT(&SendOptions, + DEFAULT_CONTROL_TRANSFER_TIMEOUT); + + WDF_USB_CONTROL_SETUP_PACKET_INIT_VENDOR(&ControlSetupPacket, + BmRequestDeviceToHost, + BmRequestToDevice, + USBFX2LK_READ_SWITCHES, + 0, + 0); + + SwitchState->SwitchesAsUChar = 0; + + WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&MemoryDescriptor, + SwitchState, + sizeof(SWITCH_STATE)); + + Status = WdfUsbTargetDeviceSendControlTransferSynchronously(DeviceContext->UsbDevice, + NULL, + &SendOptions, + &ControlSetupPacket, + &MemoryDescriptor, + &BytesTransferred); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "GetSwitchState: Failed to get switches - 0x%x \n", + Status); + } + else + { + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "GetSwitchState: Switch mask is 0x%x\n", + SwitchState->SwitchesAsUChar); + } + + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, + "<-- GetSwitchState\n"); + + return Status; +} + + +/*++ + +Routine Description + + This method handles the completion of the pending request for the IOCTL + IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE. + +Arguments: + + Device - Handle to a framework device object + +Return Value: + + VOID + +--*/ +VOID +OsrUsbIoctlGetInterruptMessage( + _In_ WDFDEVICE Device, + _In_ NTSTATUS ReaderStatus + ) +{ + NTSTATUS Status; + WDFREQUEST Request; + PDEVICE_CONTEXT DeviceContext; + size_t BytesReturned = 0; + PSWITCH_STATE SwitchState = NULL; + + DeviceContext = GetDeviceContext(Device); + + do + { + // + // Check if there are any pending requests in the Interrupt Message Queue. + // If a request is found then complete the pending request. + // + Status = WdfIoQueueRetrieveNextRequest(DeviceContext->InterruptMsgQueue, + &Request); + + if (NT_SUCCESS(Status)) + { + Status = WdfRequestRetrieveOutputBuffer(Request, + sizeof(SWITCH_STATE), + &SwitchState, + NULL); + + if (!NT_SUCCESS(Status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, + "User's output buffer is too small for this IOCTL, expecting a SWITCH_STATE\n"); + + BytesReturned = sizeof(SWITCH_STATE); + } + else + { + // + // Copy the state information saved by the continuous reader. + // + if (NT_SUCCESS(ReaderStatus)) + { + SwitchState->SwitchesAsUChar = DeviceContext->CurrentSwitchState; + BytesReturned = sizeof(SWITCH_STATE); + } + else + { + BytesReturned = 0; + } + } + + // + // Complete the request. If we failed to get the output buffer then + // complete with that status. Otherwise complete with the Status from the reader. + // + WdfRequestCompleteWithInformation(Request, + NT_SUCCESS(Status) ? ReaderStatus : + Status, + BytesReturned); + + Status = STATUS_SUCCESS; + } + else if (Status != STATUS_NO_MORE_ENTRIES) + { + KdPrint(("WdfIoQueueRetrieveNextRequest Status %08x\n", Status)); + } + + Request = NULL; + + } while (Status == STATUS_SUCCESS); +} + + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.Filters b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.Filters new file mode 100644 index 00000000..26fecf1e --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.Filters @@ -0,0 +1,302 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Source Files"> + <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;*</Extensions> + <UniqueIdentifier>{F15AAD6B-59E8-4958-90A3-552BD48EAFE2}</UniqueIdentifier> + </Filter> + <Filter Include="Header Files"> + <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> + <UniqueIdentifier>{4DD84A7D-DF53-4EE0-A484-1352320A6750}</UniqueIdentifier> + </Filter> + <Filter Include="Resource Files"> + <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml</Extensions> + <UniqueIdentifier>{EF018331-C5CB-4F90-8D54-2EF10F370E8A}</UniqueIdentifier> + </Filter> + <Filter Include="Driver Files"> + <Extensions>inf;inv;inx;mof;mc;</Extensions> + <UniqueIdentifier>{9A3958FE-0B1F-4C9F-9827-83322770EC8A}</UniqueIdentifier> + </Filter> + </ItemGroup> + <ItemGroup> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + <ClCompile Include="driver.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="device.c" /> + <ClCompile Include="ioctl.c" /> + <ClCompile Include="bulkrwr.c" /> + <ClCompile Include="Interrupt.c" /> + </ItemGroup> + <ItemGroup> + <MessageCompile Include="osrusbfx2.man"> + <Filter>Resource Files</Filter> + </MessageCompile> + </ItemGroup> + <ItemGroup> + <ClInclude Include="osrusbfx2.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="trace.h" /> + <ClInclude Include="osrusbfx2.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="trace.h" /> + <ClInclude Include="osrusbfx2.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="trace.h" /> + <ClInclude Include="osrusbfx2.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="trace.h" /> + <ClInclude Include="osrusbfx2.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="trace.h" /> + <ClInclude Include="osrusbfx2.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="trace.h" /> + <ClInclude Include="osrusbfx2.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="trace.h" /> + <ClInclude Include="osrusbfx2.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="trace.h" /> + <ClInclude Include="osrusbfx2.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="trace.h" /> + </ItemGroup> + <ItemGroup> + <Inf Include="osrfx2_DCHU_base.inx"> + <Filter>Driver Files</Filter> + </Inf> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.inx b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.inx Binary files differnew file mode 100644 index 00000000..4b37e644 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.inx diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.vcxproj b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.vcxproj new file mode 100644 index 00000000..0c4dec56 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrfx2_DCHU_base.vcxproj @@ -0,0 +1,272 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{5B711254-3F53-4E1D-A1AD-CC81E34588B7}</ProjectGuid> + <RootNamespace>$(MSBuildProjectName)</RootNamespace> + <UMDF_VERSION_MAJOR>2</UMDF_VERSION_MAJOR> + <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> + <Platform Condition="'$(Platform)' == ''">Win32</Platform> + <SampleGuid>{F915ED95-7BE9-4CDB-B09A-0D3F4C9657FE}</SampleGuid> + <ProjectName>osrfx2_DCHU_base</ProjectName> + <WindowsTargetPlatformVersion>10.0.15063.0</WindowsTargetPlatformVersion> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>False</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType>UMDF</DriverType> + <PlatformToolset>WindowsUserModeDriver10.0</PlatformToolset> + <ConfigurationType>DynamicLibrary</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>True</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType>UMDF</DriverType> + <PlatformToolset>WindowsUserModeDriver10.0</PlatformToolset> + <ConfigurationType>DynamicLibrary</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>False</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType>UMDF</DriverType> + <PlatformToolset>WindowsUserModeDriver10.0</PlatformToolset> + <ConfigurationType>DynamicLibrary</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>True</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType>UMDF</DriverType> + <PlatformToolset>WindowsUserModeDriver10.0</PlatformToolset> + <ConfigurationType>DynamicLibrary</ConfigurationType> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <PropertyGroup> + <OutDir>$(SolutionDir)$(Platform)\$(ConfigurationName)\</OutDir> + </PropertyGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ItemGroup Label="WrappedTaskItems"> + <ClCompile Include="driver.c; device.c; ioctl.c; bulkrwr.c; Interrupt.c"> + <WppEnabled>true</WppEnabled> + <WppDllMacro>true</WppDllMacro> + <WppTraceFunction>TraceEvents(LEVEL,FLAGS,MSG,...)</WppTraceFunction> + <WppGenerateUsingTemplateFile>{um-default.tpl}*.tmh</WppGenerateUsingTemplateFile> + <WppPreprocessorDefinitions>ENABLE_WPP_RECORDER=1;WPP_MACRO_USE_KM_VERSION_FOR_UM=1</WppPreprocessorDefinitions> + </ClCompile> + <MessageCompile Include="osrusbfx2.man"> + <GenerateUserModeLoggingMacros>true</GenerateUserModeLoggingMacros> + <GenerateMofFile>true</GenerateMofFile> + <HeaderFilePath>.\$(IntDir)</HeaderFilePath> + <GeneratedHeaderPath>true</GeneratedHeaderPath> + <RCFilePath>.\$(IntDir)</RCFilePath> + <GeneratedRCAndMessagesPath>true</GeneratedRCAndMessagesPath> + <GeneratedFilesBaseName>fx2Events</GeneratedFilesBaseName> + <UseBaseNameOfInput>true</UseBaseNameOfInput> + <SubType>Designer</SubType> + </MessageCompile> + </ItemGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <TargetName>osrfx2_DCHU_base</TargetName> + <ALLOW_DATE_TIME>1</ALLOW_DATE_TIME> + <ApiValidator_Enable>false</ApiValidator_Enable> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <TargetName>osrfx2_DCHU_base</TargetName> + <ALLOW_DATE_TIME>1</ALLOW_DATE_TIME> + <ApiValidator_Enable>false</ApiValidator_Enable> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <TargetName>osrfx2_DCHU_base</TargetName> + <ALLOW_DATE_TIME>1</ALLOW_DATE_TIME> + <ApiValidator_Enable>false</ApiValidator_Enable> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <TargetName>osrfx2_DCHU_base</TargetName> + <ALLOW_DATE_TIME>1</ALLOW_DATE_TIME> + <ApiValidator_Enable>false</ApiValidator_Enable> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + <WppEnabled>true</WppEnabled> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);$(SDK_LIB_PATH)\onecore.lib;$(SDK_LIB_PATH)\WppRecorderUM.lib</AdditionalDependencies> + <IgnoreSpecificDefaultLibraries /> + </Link> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + <WppEnabled>true</WppEnabled> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);$(SDK_LIB_PATH)\onecore.lib;$(SDK_LIB_PATH)\WppRecorderUM.lib</AdditionalDependencies> + <IgnoreSpecificDefaultLibraries /> + </Link> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + <WppEnabled>true</WppEnabled> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);$(SDK_LIB_PATH)\onecore.lib;$(SDK_LIB_PATH)\WppRecorderUM.lib</AdditionalDependencies> + <IgnoreSpecificDefaultLibraries /> + </Link> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + <WppEnabled>true</WppEnabled> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);EVENT_TRACING;UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);$(SDK_LIB_PATH)\onecore.lib;$(SDK_LIB_PATH)\WppRecorderUM.lib</AdditionalDependencies> + <IgnoreSpecificDefaultLibraries /> + </Link> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemGroup> + <FilesToPackage Include="$(SolutionDir)$(Platform)\$(ConfigurationName)\osrfx2_DCHU_base.dll" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <FilesToPackage Include="$(SolutionDir)$(Platform)\$(ConfigurationName)\osrfx2_DCHU_filter.dll" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <FilesToPackage Include="$(SolutionDir)$(Platform)\$(ConfigurationName)\osrfx2_DCHU_usersvc.exe" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <FilesToPackage Include="$(SolutionDir)$(Platform)\$(ConfigurationName)\osrfx2_DCHU_filter.dll" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <FilesToPackage Include="$(SolutionDir)$(Platform)\$(ConfigurationName)\osrfx2_DCHU_usersvc.exe" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <FilesToPackage Include="$(SolutionDir)$(Platform)\$(ConfigurationName)\osrfx2_DCHU_filter.dll" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <FilesToPackage Include="$(SolutionDir)$(Platform)\$(ConfigurationName)\osrfx2_DCHU_usersvc.exe" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <FilesToPackage Include="$(SolutionDir)$(Platform)\$(ConfigurationName)\osrfx2_DCHU_filter.dll" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <FilesToPackage Include="$(SolutionDir)$(Platform)\$(ConfigurationName)\osrfx2_DCHU_usersvc.exe" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <Inf Include="osrfx2_DCHU_base.inx" /> + </ItemGroup> + <ItemGroup> + <None Exclude="@(None)" Include="*.txt;*.htm;*.html" /> + <None Exclude="@(None)" Include="*.ico;*.cur;*.bmp;*.dlg;*.rct;*.gif;*.jpg;*.jpeg;*.wav;*.jpe;*.tiff;*.tif;*.png;*.rc2" /> + <None Exclude="@(None)" Include="*.def;*.bat;*.hpj;*.asmx" /> + </ItemGroup> + <ItemGroup> + <ClInclude Exclude="@(ClInclude)" Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd" /> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrusbfx2.h b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrusbfx2.h new file mode 100644 index 00000000..d35086de --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrusbfx2.h @@ -0,0 +1,312 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + osrusbfx2.h + +Abstract: + + Contains structure definitions and function prototypes private to + the driver. + +Environment: + + User mode + +--*/ + +#include <windows.h> +#include <winioctl.h> +#pragma warning( disable: 4201 ) // nonstandard extension used : nameless struct/union +#include <ntstatus.h> +#include <assert.h> +#include <strsafe.h> +#include <devpropdef.h> +#include <wudfwdm.h> +typedef struct _IO_STACK_LOCATION *PIO_STACK_LOCATION; +#include <usbdi.h> +#include <wdf.h> +#include <wdfusb.h> +#include <prototypes.h> +#include <initguid.h> +#include <driverspecs.h> +#include "trace.h" + +#include "public.h" + +// +// Include auto-generated ETW event functions (created by MC.EXE from +// osrusbfx2.man) +// +#include <evntprov.h> +#include "fx2Events.h" + +#ifndef _PRIVATE_H +#define _PRIVATE_H + +#define POOL_TAG (ULONG) 'FRSO' +#define _DRIVER_NAME_ "OSRUSBFX2" + +#define TEST_BOARD_TRANSFER_BUFFER_SIZE (64*1024) +#define DEVICE_DESC_LENGTH 256 + +extern const __declspec(selectany) LONGLONG DEFAULT_CONTROL_TRANSFER_TIMEOUT = 5 * -1 * WDF_TIMEOUT_TO_SEC; + +// +// Define the vendor commands supported by our device +// +#define USBFX2LK_READ_7SEGMENT_DISPLAY 0xD4 +#define USBFX2LK_READ_SWITCHES 0xD6 +#define USBFX2LK_READ_BARGRAPH_DISPLAY 0xD7 +#define USBFX2LK_SET_BARGRAPH_DISPLAY 0xD8 +#define USBFX2LK_IS_HIGH_SPEED 0xD9 +#define USBFX2LK_REENUMERATE 0xDA +#define USBFX2LK_SET_7SEGMENT_DISPLAY 0xDB + +// +// Define the features that we can clear +// and set on our device +// +#define USBFX2LK_FEATURE_EPSTALL 0x00 +#define USBFX2LK_FEATURE_WAKE 0x01 + +// +// Order of endpoints in the interface descriptor +// +#define INTERRUPT_IN_ENDPOINT_INDEX 0 +#define BULK_OUT_ENDPOINT_INDEX 1 +#define BULK_IN_ENDPOINT_INDEX 2 + +// +// A structure representing the instance information associated with +// this particular device. +// + +typedef struct _DEVICE_CONTEXT { + + WDFUSBDEVICE UsbDevice; + + WDFUSBINTERFACE UsbInterface; + + WDFUSBPIPE BulkReadPipe; + + WDFUSBPIPE BulkWritePipe; + + WDFUSBPIPE InterruptPipe; + + WDFWAITLOCK ResetDeviceWaitLock; + + UCHAR CurrentSwitchState; + + WDFQUEUE InterruptMsgQueue; + + ULONG UsbDeviceTraits; + + // + // The following fields are used during event logging to + // report the events relative to this specific instance + // of the device. + // + + WDFMEMORY DeviceNameMemory; + PCWSTR DeviceName; + + WDFMEMORY LocationMemory; + PCWSTR Location; + +} DEVICE_CONTEXT, *PDEVICE_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DEVICE_CONTEXT, GetDeviceContext) + +extern ULONG DebugLevel; + +typedef +NTSTATUS +(*PFN_IO_GET_ACTIVITY_ID_IRP) ( + _In_ PIRP Irp, + _Out_ LPGUID Guid + ); + +typedef +NTSTATUS +(*PFN_IO_SET_DEVICE_INTERFACE_PROPERTY_DATA) ( + _In_ PUNICODE_STRING SymbolicLinkName, + _In_ CONST DEVPROPKEY *PropertyKey, + _In_ LCID Lcid, + _In_ ULONG Flags, + _In_ DEVPROPTYPE Type, + _In_ ULONG Size, + _In_opt_ PVOID Data + ); + +DRIVER_INITIALIZE DriverEntry; + +EVT_WDF_OBJECT_CONTEXT_CLEANUP OsrFxEvtDriverContextCleanup; + +EVT_WDF_DRIVER_DEVICE_ADD OsrFxEvtDeviceAdd; + +EVT_WDF_DEVICE_PREPARE_HARDWARE OsrFxEvtDevicePrepareHardware; + +EVT_WDF_IO_QUEUE_IO_READ OsrFxEvtIoRead; + +EVT_WDF_IO_QUEUE_IO_WRITE OsrFxEvtIoWrite; + +EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL OsrFxEvtIoDeviceControl; + +EVT_WDF_REQUEST_COMPLETION_ROUTINE EvtRequestReadCompletionRoutine; + +EVT_WDF_REQUEST_COMPLETION_ROUTINE EvtRequestWriteCompletionRoutine; + +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +ResetPipe( + _In_ WDFUSBPIPE Pipe + ); + +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +ResetDevice( + _In_ WDFDEVICE Device + ); + +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +SelectInterfaces( + _In_ WDFDEVICE Device + ); + +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +ReenumerateDevice( + _In_ PDEVICE_CONTEXT DevContext + ); + +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +GetBarGraphState( + _In_ PDEVICE_CONTEXT DevContext, + _Out_ PBAR_GRAPH_STATE BarGraphState + ); + +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +SetBarGraphState( + _In_ PDEVICE_CONTEXT DevContext, + _In_ PBAR_GRAPH_STATE BarGraphState + ); + +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +GetSevenSegmentState( + _In_ PDEVICE_CONTEXT DevContext, + _Out_ PUCHAR SevenSegment + ); + +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +SetSevenSegmentState( + _In_ PDEVICE_CONTEXT DevContext, + _In_ PUCHAR SevenSegment + ); + +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +GetSwitchState( + _In_ PDEVICE_CONTEXT DevContext, + _In_ PSWITCH_STATE SwitchState + ); + +VOID +OsrUsbIoctlGetInterruptMessage( + _In_ WDFDEVICE Device, + _In_ NTSTATUS ReaderStatus + ); + +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +OsrFxSetPowerPolicy( + _In_ WDFDEVICE Device + ); + +_IRQL_requires_(PASSIVE_LEVEL) +NTSTATUS +OsrFxConfigContReaderForInterruptEndPoint( + _In_ PDEVICE_CONTEXT DeviceContext + ); + +EVT_WDF_USB_READER_COMPLETION_ROUTINE OsrFxEvtUsbInterruptPipeReadComplete; + +EVT_WDF_USB_READERS_FAILED OsrFxEvtUsbInterruptReadersFailed; + +EVT_WDF_IO_QUEUE_IO_STOP OsrFxEvtIoStop; + +EVT_WDF_DEVICE_D0_ENTRY OsrFxEvtDeviceD0Entry; + +EVT_WDF_DEVICE_D0_EXIT OsrFxEvtDeviceD0Exit; + +EVT_WDF_DEVICE_SELF_MANAGED_IO_FLUSH OsrFxEvtDeviceSelfManagedIoFlush; + +_IRQL_requires_(PASSIVE_LEVEL) +BOOLEAN +OsrFxReadFdoRegistryKeyValue( + _In_ PWDFDEVICE_INIT DeviceInit, + _In_ PWCHAR Name, + _Out_ PULONG Value + ); + +_IRQL_requires_max_(DISPATCH_LEVEL) +VOID +OsrFxEnumerateChildren( + _In_ WDFDEVICE Device + ); + +_IRQL_requires_(PASSIVE_LEVEL) +VOID +GetDeviceEventLoggingNames( + _In_ WDFDEVICE Device + ); + +_IRQL_requires_(PASSIVE_LEVEL) +PCHAR +DbgDevicePowerString( + _In_ WDF_POWER_DEVICE_STATE Type + ); + +FORCEINLINE +GUID +RequestToActivityId( + _In_ WDFREQUEST Request + ) +{ + GUID activity = {0}; + + // + // Use the WDFREQUEST handle as the activity ID + // + RtlCopyMemory(&activity, &Request, sizeof(WDFREQUEST)); + + return activity; +} + +FORCEINLINE +GUID +DeviceToActivityId( + _In_ WDFDEVICE Device + ) +{ + GUID activity = {0}; + RtlCopyMemory(&activity, &Device, sizeof(WDFDEVICE)); + return activity; +} + + +#endif + + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrusbfx2.man b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrusbfx2.man new file mode 100644 index 00000000..19f363d5 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrusbfx2.man @@ -0,0 +1,309 @@ +<?xml version='1.0' encoding='utf-8' standalone='yes'?> +<instrumentationManifest + xmlns="http://schemas.microsoft.com/win/2004/08/events" + xmlns:win="http://manifests.microsoft.com/win/2004/08/windows/events" + xmlns:xs="http://www.w3.org/2001/XMLSchema" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://schemas.microsoft.com/win/2004/08/events eventman.xsd" + > + <instrumentation> + <events> + <provider + guid="{69cd60e3-430f-4da4-b1b3-e3bdaf945875}" + messageFileName="%Systemroot%\System32\drivers\umdf\osrusbfx2um.dll" + name="OSRUSBFX2" + resourceFileName="%SystemRoot%\System32\drivers\umdf\osrusbfx2um.dll" + symbol="OSRUSBFX2_PROVIDER" + > + <channels> + <channel + chid="Analytic" + enabled="false" + name="OsrUsbfx2/Analytic" + symbol="OSRUSBFX2_ANALYTIC" + type="Analytic" + /> + <channel + chid="operational" + enabled="true" + isolation="System" + message="$(string.OSRUSBFX2_OPERATIONAL.Name)" + name="OsrUsbFx2/Operational" + symbol="OSRUSBFX2_OPERATIONAL" + type="Operational" + /> + </channels> + <keywords> + <keyword + mask="0x0000000000000010" + message="$(string.OSRUSBFX2_DEVICE_INFO_KEYWORD.message)" + name="deviceinfo" + symbol="OSRUSBFX2_DEVICE_INFO_KEYWORD" + /> + <keyword + mask="0x0000000000000040" + message="$(string.OSRUSBFX2_READ_WRITE_KEYWORD.message)" + name="readwrite" + symbol="OSRUSBFX2_READ_WRITE_KEYWORD" + /> + </keywords> + <opcodes> + <!-- Defining our own custom opcode instead of using standard opcodes defined by winmeta.xml --> + <opcode + name="add" + symbol="OSRUSBFX2_DEVICE_ADD" + value="10" + /> + <opcode + name="fail" + symbol="OSRUSBFX2_FAIL" + value="11" + /> + </opcodes> + <tasks> + <!-- Support for XP and W2K3 : MC.exe will create a MOF file --> + <!-- Requires an associated eventGUID attribute for each task that is defined --> + <!-- For the MOF file : --> + <!-- Semantically, the event GUID represents a set of logical events that are logged by the provider. --> + <task + eventGUID="{872c3c43-6899-4f1d-89b8-51a82f6db657}" + name="deviceInit" + symbol="OSRUSBFX2_DEVICE_INIT" + value="1" + /> + <task + eventGUID="{872c3c45-6899-4f1d-89b8-51a82f6db657}" + name="read" + symbol="OSRUSBFX2_READ" + value="2" + /> + <task + eventGUID="{872c3c46-6899-4f1d-89b8-51a82f6db657}" + name="write" + symbol="OSRUSBFX2_WRITE" + value="3" + /> + </tasks> + <templates> + <template tid="tid_DeviceStatus"> + <data + inType="win:UnicodeString" + name="FriendlyName" + outType="xs:string" + /> + <data + inType="win:UnicodeString" + name="Location" + outType="xs:string" + /> + <data + inType="win:UInt32" + name="NTStatus" + outType="xs:HexInt32" + /> + </template> + <template tid="tid_ReadWrite"> + <data + inType="win:Pointer" + name="Device" + outType="win:HexInt64" + /> + <data + inType="win:UInt32" + name="Length" + outType="xs:unsignedInt" + /> + </template> + <template tid="tid_ReadWriteFail"> + <data + inType="win:Pointer" + name="Device" + outType="win:HexInt64" + /> + <data + inType="win:UInt32" + name="NTStatus" + outType="xs:HexInt32" + /> + </template> + <template tid="tid_ReadWriteCompletion"> + <data + inType="win:Pointer" + name="Device" + outType="win:HexInt64" + /> + <data + inType="win:UInt32" + name="Length" + outType="xs:unsignedInt" + /> + <data + inType="win:UInt32" + name="NTStatus" + outType="xs:HexInt32" + /> + <data + inType="win:UInt32" + name="UsbdStatus" + outType="xs:unsignedInt" + /> + </template> + </templates> + <events> + <event + channel="Analytic" + keywords="readwrite" + message="$(string.ReadStart.EventMessage)" + level="win:Informational" + opcode="win:Start" + symbol="ReadStart" + task="read" + template="tid_ReadWrite" + value="1" + /> + <event + channel="Analytic" + keywords="readwrite" + message="$(string.ReadStop.EventMessage)" + level="win:Informational" + opcode="win:Stop" + symbol="ReadStop" + task="read" + template="tid_ReadWriteCompletion" + value="2" + /> + <event + channel="Analytic" + keywords="readwrite" + message="$(string.ReadFail.EventMessage)" + level="win:Error" + opcode="fail" + symbol="ReadFail" + task="read" + template="tid_ReadWriteFail" + value="3" + /> + <event + channel="Analytic" + keywords="readwrite" + message="$(string.WriteStart.EventMessage)" + level="win:Informational" + opcode="win:Start" + symbol="WriteStart" + task="write" + template="tid_ReadWrite" + value="4" + /> + <event + channel="Analytic" + keywords="readwrite" + message="$(string.WriteStop.EventMessage)" + level="win:Informational" + opcode="win:Stop" + symbol="WriteStop" + task="write" + template="tid_ReadWriteCompletion" + value="5" + /> + <event + channel="Analytic" + keywords="readwrite" + message="$(string.WriteFail.EventMessage)" + level="win:Error" + opcode="fail" + symbol="WriteFail" + task="write" + template="tid_ReadWriteFail" + value="6" + /> + <event + channel="operational" + keywords="deviceinfo" + level="win:Error" + message="$(string.DeviceFailAdd.EventMessage)" + opcode="add" + symbol="FailAddDevice" + task="deviceInit" + template="tid_DeviceStatus" + value="100" + /> + <event + channel="operational" + keywords="deviceinfo" + message="$(string.DeviceReenumerated.EventMessage)" + opcode="win:Start" + symbol="DeviceReenumerated" + task="deviceInit" + template="tid_DeviceStatus" + value="101" + /> + <event + channel="operational" + keywords="deviceinfo" + level="win:Error" + message="$(string.SelectConfigFailure.Message)" + opcode="fail" + symbol="SelectConfigFailure" + task="deviceInit" + template="tid_DeviceStatus" + value="102" + /> + </events> + </provider> + </events> + </instrumentation> + <localization xmlns="http://schemas.microsoft.com/win/2004/08/events"> + <resources culture="en-US"> + <stringTable> + <string + id="OSRUSBFX2_DEVICE_INFO_KEYWORD.message" + value="Device events: fail to load, reenumerate" + /> + <string + id="OSRUSBFX2_READ_WRITE_KEYWORD.message" + value="Read, Write events" + /> + <string + id="OSRUSBFX2_OPERATIONAL.Name" + value="Operational channel eventlog" + /> + <string + id="ReadStart.EventMessage" + value="Read. Device = %1, Length = %2" + /> + <string + id="ReadStop.EventMessage" + value="Read complete. Device = %1, Length = %2, Status = %3, UsbStatus = %4" + /> + <string + id="ReadFail.EventMessage" + value="Read error. Device = %1, Status = %2" + /> + <string + id="WriteStart.EventMessage" + value="Write. Device = %1, Length = %2" + /> + <string + id="WriteStop.EventMessage" + value="Write complete. Device = %1, Length = %2, Status = %3, UsbStatus = %4" + /> + <string + id="WriteFail.EventMessage" + value="Write error. Device = %1, Status = %2" + /> + <string + id="DeviceReenumerated.EventMessage" + value="Device %1 (location %2) was reenumerated" + /> + <string + id="DeviceFailAdd.EventMessage" + value="Fail to add device %1 (location %2), status %3" + /> + <string + id="SelectConfigFailure.Message" + value="This error occurs when an OSR USB Fx2 board is attached to a USB 1.1 port on a machine running Windows Vista. This error occurs because the OSR USB Fx2 board's Interrupt end-point descriptor does not conform to the USB specification. Windows Vista detects this and returns an error. You should plug the device into a USB 2.0 (or higher) port." + /> + </stringTable> + </resources> + </localization> +</instrumentationManifest> diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrusbfx2.rc b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrusbfx2.rc new file mode 100644 index 00000000..84f89a6c --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/osrusbfx2.rc @@ -0,0 +1,13 @@ +#include <windows.h> + +#include <ntverp.h> + +#define VER_FILETYPE VFT_DLL +#define VER_FILESUBTYPE VFT_UNKNOWN +#define VER_FILEDESCRIPTION_STR "WDF Sample Driver for OSR USB-FX2 Learning Kit" +#define VER_INTERNALNAME_STR "osrusbfx2um.dll" +#define VER_ORIGINALFILENAME_STR "osrusbfx2um.dll" + +#include "common.ver" + +#include "fx2Events.rc" diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/trace.h b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/trace.h new file mode 100644 index 00000000..5a72dcaf --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_base/trace.h @@ -0,0 +1,115 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + TRACE.h + +Abstract: + + Header file for the debug tracing related function defintions and macros. + +Environment: + + Kernel mode + +--*/ + +#include <evntrace.h> // For TRACE_LEVEL definitions + +#if !defined(EVENT_TRACING) + +// +// TODO: These defines are missing in evntrace.h +// in some DDK build environments (XP). +// +#if !defined(TRACE_LEVEL_NONE) + #define TRACE_LEVEL_NONE 0 + #define TRACE_LEVEL_CRITICAL 1 + #define TRACE_LEVEL_FATAL 1 + #define TRACE_LEVEL_ERROR 2 + #define TRACE_LEVEL_WARNING 3 + #define TRACE_LEVEL_INFORMATION 4 + #define TRACE_LEVEL_VERBOSE 5 + #define TRACE_LEVEL_RESERVED6 6 + #define TRACE_LEVEL_RESERVED7 7 + #define TRACE_LEVEL_RESERVED8 8 + #define TRACE_LEVEL_RESERVED9 9 +#endif + + +// +// Define Debug Flags +// +#define DBG_INIT 0x00000001 +#define DBG_PNP 0x00000002 +#define DBG_POWER 0x00000004 +#define DBG_WMI 0x00000008 +#define DBG_CREATE_CLOSE 0x00000010 +#define DBG_IOCTL 0x00000020 +#define DBG_WRITE 0x00000040 +#define DBG_READ 0x00000080 + + +VOID +TraceEvents ( + _In_ ULONG DebugPrintLevel, + _In_ ULONG DebugPrintFlag, + _Printf_format_string_ + _In_ PCSTR DebugMessage, + ... + ); + +#define WPP_INIT_TRACING(RegistryPath) +#define WPP_CLEANUP() + +#else +// +// If software tracing is defined in the sources file.. +// WPP_DEFINE_CONTROL_GUID specifies the GUID used for this driver. +// *** REPLACE THE GUID WITH YOUR OWN UNIQUE ID *** +// WPP_DEFINE_BIT allows setting debug bit masks to selectively print. +// The names defined in the WPP_DEFINE_BIT call define the actual names +// that are used to control the level of tracing for the control guid +// specified. +// +// NOTE: If you are adopting this sample for your driver, please generate +// a new guid, using tools\other\i386\guidgen.exe present in the +// DDK. +// +// Name of the logger is OSRUSBFX2 and the guid is +// {D23A0C5A-D307-4f0e-AE8E-E2A355AD5DAB} +// (0xd23a0c5a, 0xd307, 0x4f0e, 0xae, 0x8e, 0xe2, 0xa3, 0x55, 0xad, 0x5d, 0xab); +// + +#define WPP_CHECK_FOR_NULL_STRING //to prevent exceptions due to NULL strings + +#define WPP_CONTROL_GUIDS \ + WPP_DEFINE_CONTROL_GUID(OsrUsbFxTraceGuid,(d23a0c5a,d307,4f0e,ae8e,E2A355AD5DAB), \ + WPP_DEFINE_BIT(DBG_INIT) /* bit 0 = 0x00000001 */ \ + WPP_DEFINE_BIT(DBG_PNP) /* bit 1 = 0x00000002 */ \ + WPP_DEFINE_BIT(DBG_POWER) /* bit 2 = 0x00000004 */ \ + WPP_DEFINE_BIT(DBG_WMI) /* bit 3 = 0x00000008 */ \ + WPP_DEFINE_BIT(DBG_CREATE_CLOSE) /* bit 4 = 0x00000010 */ \ + WPP_DEFINE_BIT(DBG_IOCTL) /* bit 5 = 0x00000020 */ \ + WPP_DEFINE_BIT(DBG_WRITE) /* bit 6 = 0x00000040 */ \ + WPP_DEFINE_BIT(DBG_READ) /* bit 7 = 0x00000080 */ \ + /* You can have up to 32 defines. If you want more than that,\ + you have to provide another trace control GUID */\ + ) + + +#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) WPP_LEVEL_LOGGER(flags) +#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) + + +#endif + + + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/filter.c b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/filter.c new file mode 100644 index 00000000..3e41778e --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/filter.c @@ -0,0 +1,421 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + filter.c + +Abstract: + + This module shows how to a write a generic filter driver. The driver demonstrates how + to support device I/O control requests through queues. All I/O requests are passed on to + the lower driver. This filter driver shows how to handle IRP postprocessing by forwarding + the requests with and without a completion routine. To forward with a completion routine + set the define FORWARD_REQUEST_WITH_COMPLETION to 1. + +Environment: + + User mode + +--*/ + +#include "filter.h" + + +#ifdef ALLOC_PRAGMA +#pragma alloc_text (INIT, DriverEntry) +#pragma alloc_text (PAGE, FilterEvtDeviceAdd) +#endif + + +/*++ + +Routine Description: + + Installable driver initialization entry point. + This entry point is called directly by the I/O system. + +Arguments: + + DriverObject - Pointer to the driver object + + RegistryPath - Pointer to a unicode string representing the path + to the driver-specific key in the registry. + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL otherwise. + +--*/ +NTSTATUS +DriverEntry( + IN PDRIVER_OBJECT DriverObject, + IN PUNICODE_STRING RegistryPath + ) +{ + WDF_DRIVER_CONFIG Config; + NTSTATUS Status; + WDFDRIVER hDriver; + + KdPrint(("Generic Upper Filter Driver Sample - Driver Framework Edition.\n")); + + // + // Initialize driver config to control the attributes that + // are global to the driver. Note that the framework by default + // provides a driver unload routine. If you created any resources + // in DriverEntry and want them to be cleaned up when the driver unloads, + // you can override that by manually setting the EvtDriverUnload in the + // config structure. In general xxx_CONFIG_INIT macros are provided to + // initialize most commonly used members. + // + + WDF_DRIVER_CONFIG_INIT(&Config, + FilterEvtDeviceAdd); + + // + // Create a framework driver object to represent our driver. + // + Status = WdfDriverCreate(DriverObject, + RegistryPath, + WDF_NO_OBJECT_ATTRIBUTES, + &Config, + &hDriver); + + if (!NT_SUCCESS(Status)) + { + KdPrint(("WdfDriverCreate failed with status 0x%x\n", Status)); + } + + return Status; +} + + +/*++ +Routine Description: + + EvtDeviceAdd is called by the framework in response to the AddDevice + call from the PnP manager. Here you can query the device properties + using WdfFdoInitWdmGetPhysicalDevice/IoGetDeviceProperty and based + on that, decide to create a filter device object and attach it to the + function stack. If you are not interested in filtering this particular + instance of the device, you can just return STATUS_SUCCESS without creating + a framework device. + +Arguments: + + Driver - Handle to a framework driver object created in DriverEntry + + DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure. + +Return Value: + + NTSTATUS + +--*/ +NTSTATUS +FilterEvtDeviceAdd( + IN WDFDRIVER Driver, + IN PWDFDEVICE_INIT DeviceInit + ) +{ + WDF_OBJECT_ATTRIBUTES DeviceAttributes; + PFILTER_EXTENSION FilterExt; + NTSTATUS Status; + WDFDEVICE Device; + WDF_IO_QUEUE_CONFIG IoQueueConfig; + + PAGED_CODE (); + + UNREFERENCED_PARAMETER(Driver); + + // + // Tell the framework that you are a filter driver. The framework + // takes care of inherting all the device flags & characteristics + // from the higher device that you are attaching to. + // + WdfFdoInitSetFilter(DeviceInit); + + // + // Specify the size of the device extension where we track per device + // context. + // + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&DeviceAttributes, FILTER_EXTENSION); + + // + // Create a framework device object. This call will in turn create + // a WDM device object, attach it to the lower stack, and set the + // appropriate flags and attributes. + // + Status = WdfDeviceCreate(&DeviceInit, &DeviceAttributes, &Device); + + if (!NT_SUCCESS(Status)) + { + KdPrint(("WdfDeviceCreate failed with status code 0x%x\n", Status)); + return Status; + } + + FilterExt = FilterGetData(Device); + + // + // Configure the default queue to be Parallel. + // + WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&IoQueueConfig, + WdfIoQueueDispatchParallel); + + // + // The framework by default creates non-power managed queues for + // filter drivers. + // + IoQueueConfig.EvtIoDeviceControl = FilterEvtIoDeviceControl; + + Status = WdfIoQueueCreate(Device, + &IoQueueConfig, + WDF_NO_OBJECT_ATTRIBUTES, + WDF_NO_HANDLE // Pointer to default queue + ); + + if (!NT_SUCCESS(Status)) + { + KdPrint(("WdfIoQueueCreate failed 0x%x\n", Status)); + return Status; + } + + return Status; +} + + +/*++ + +Routine Description: + + This routine is the dispatch routine for internal device control requests. + +Arguments: + + Queue - Handle to the framework queue object that is associated + with the I/O request + + Request - Handle to a framework request object + + OutputBufferLength - Length of the request's output buffer, + if an output buffer is available + + InputBufferLength - Length of the request's input buffer, + if an input buffer is available + + IoControlCode - The driver-defined or system-defined I/O control code + (IOCTL) that is associated with the request + +Return Value: + + VOID + +--*/ +VOID +FilterEvtIoDeviceControl( + IN WDFQUEUE Queue, + IN WDFREQUEST Request, + IN size_t OutputBufferLength, + IN size_t InputBufferLength, + IN ULONG IoControlCode + ) +{ + PFILTER_EXTENSION FilterExt; + NTSTATUS Status = STATUS_SUCCESS; + WDFDEVICE Device; + + UNREFERENCED_PARAMETER(OutputBufferLength); + UNREFERENCED_PARAMETER(InputBufferLength); + + KdPrint(("Entered FilterEvtIoDeviceControl\n")); + + Device = WdfIoQueueGetDevice(Queue); + + FilterExt = FilterGetData(Device); + + switch (IoControlCode) + { + + // + // Put your cases for handling IOCTLs here + // + + default: + Status = STATUS_SUCCESS; + } + + if (!NT_SUCCESS(Status)) + { + WdfRequestComplete(Request, Status); + return; + } + + // + // Forward the request down. WdfDeviceGetIoTarget returns + // the default target, which represents the device attached to us below in + // the stack. + // +#if FORWARD_REQUEST_WITH_COMPLETION + // + // Use this routine to forward a request if you are interested in post + // processing the IRP. + // + FilterForwardRequestWithCompletionRoutine(Request, + WdfDeviceGetIoTarget(Device)); +#else + FilterForwardRequest(Request, WdfDeviceGetIoTarget(Device)); +#endif + + return; +} + + +/*++ +Routine Description: + + Passes a request on to the lower driver. + +Arguments: + + Request - The request to pass on to the lower driver + + Target - The lower driver to pass the request to + +Return Value: + + VOID + +--*/ +VOID +FilterForwardRequest( + IN WDFREQUEST Request, + IN WDFIOTARGET Target + ) +{ + WDF_REQUEST_SEND_OPTIONS Options; + BOOLEAN RequestSent; + NTSTATUS Status; + + // + // We are not interested in post processing the IRP so + // fire and forget. + // + WDF_REQUEST_SEND_OPTIONS_INIT(&Options, + WDF_REQUEST_SEND_OPTION_SEND_AND_FORGET); + + RequestSent = WdfRequestSend(Request, Target, &Options); + + if (RequestSent == FALSE) { + Status = WdfRequestGetStatus(Request); + KdPrint(("WdfRequestSend failed: 0x%x\n", Status)); + WdfRequestComplete(Request, Status); + } + + return; +} + +#if FORWARD_REQUEST_WITH_COMPLETION + +VOID +FilterForwardRequestWithCompletionRoutine( + IN WDFREQUEST Request, + IN WDFIOTARGET Target + ) +/*++ +Routine Description: + + This routine forwards the request to a lower driver with + a completion so that when the request is completed by the + lower driver, it can regain control of the request and look + at the result. + +Arguments: + + Request - The request to pass on to the lower driver + + Target - The lower driver to pass the request to + +Return Value: + + VOID + +--*/ +{ + BOOLEAN RequestSent; + NTSTATUS Status; + + // + // The following function essentially copies the content of the + // current stack location of the underlying IRP to the next one. + // + WdfRequestFormatRequestUsingCurrentType(Request); + + WdfRequestSetCompletionRoutine(Request, + FilterRequestCompletionRoutine, + WDF_NO_CONTEXT); + + RequestSent = WdfRequestSend(Request, + Target, + WDF_NO_SEND_OPTIONS); + + if (RequestSent == FALSE) + { + Status = WdfRequestGetStatus(Request); + KdPrint(("WdfRequestSend failed: 0x%x\n", Status)); + WdfRequestComplete(Request, Status); + } + + return; +} + + +/*++ + +Routine Description: + + Completion Routine. + +Arguments: + + Target - Target handle + + Request - Request handle + + Params - Request completion params + + Context - Driver supplied context + +Return Value: + + VOID + +--*/ +VOID +FilterRequestCompletionRoutine( + IN WDFREQUEST Request, + IN WDFIOTARGET Target, + PWDF_REQUEST_COMPLETION_PARAMS CompletionParams, + IN WDFCONTEXT Context + ) +{ + UNREFERENCED_PARAMETER(Target); + UNREFERENCED_PARAMETER(Context); + + WdfRequestComplete(Request, CompletionParams->IoStatus.Status); + + return; +} + +#endif //FORWARD_REQUEST_WITH_COMPLETION + + + + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/filter.h b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/filter.h new file mode 100644 index 00000000..e9042c29 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/filter.h @@ -0,0 +1,85 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + filter.h + +Abstract: + + Contains structure definitions and function prototypes for a generic filter driver. + +Environment: + + User mode + +--*/ + +#include <windows.h> +#include <winioctl.h> +#pragma warning( disable: 4201 ) // nonstandard extension used : nameless struct/union +#include <ntstatus.h> +#include <devpropdef.h> +#include <wudfwdm.h> +#include <wdf.h> + +#if !defined(_FILTER_H_) +#define _FILTER_H_ + + +#define DRIVERNAME "Generic.sys: " + +// +// Change the following define to 1 if you want to forward +// the request with a completion routine. +// +#define FORWARD_REQUEST_WITH_COMPLETION 0 + + +typedef struct _FILTER_EXTENSION +{ + WDFDEVICE WdfDevice; + // More context data here + +}FILTER_EXTENSION, *PFILTER_EXTENSION; + + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(FILTER_EXTENSION, + FilterGetData) + +DRIVER_INITIALIZE DriverEntry; +EVT_WDF_DRIVER_DEVICE_ADD FilterEvtDeviceAdd; +EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL FilterEvtIoDeviceControl; + +VOID +FilterForwardRequest( + IN WDFREQUEST Request, + IN WDFIOTARGET Target + ); + +#if FORWARD_REQUEST_WITH_COMPLETION + +VOID +FilterForwardRequestWithCompletionRoutine( + IN WDFREQUEST Request, + IN WDFIOTARGET Target + ); + +VOID +FilterRequestCompletionRoutine( + IN WDFREQUEST Request, + IN WDFIOTARGET Target, + PWDF_REQUEST_COMPLETION_PARAMS CompletionParams, + IN WDFCONTEXT Context + ); + +#endif //FORWARD_REQUEST_WITH_COMPLETION + +#endif + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/filter.rc b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/filter.rc new file mode 100644 index 00000000..0c108f44 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/filter.rc @@ -0,0 +1,12 @@ +#include <windows.h> +#include <filter.h> +#include <ntverp.h> + +#define VER_FILETYPE VFT_DLL +#define VER_FILESUBTYPE VFT_UNKNOWN +#define VER_FILEDESCRIPTION_STR "UMDF 2.0 Filter Driver for the Toaster Stack" +#define VER_INTERNALNAME_STR DRIVERNAME +#define VER_ORIGINALFILENAME_STR DRIVERNAME + +#include "common.ver" + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/osrfx2_DCHU_filter.Filters b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/osrfx2_DCHU_filter.Filters new file mode 100644 index 00000000..2e7de4fc --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/osrfx2_DCHU_filter.Filters @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Source Files"> + <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;*</Extensions> + <UniqueIdentifier>{B98D4FD9-00A8-4964-AE34-6AF1F833564B}</UniqueIdentifier> + </Filter> + <Filter Include="Header Files"> + <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> + <UniqueIdentifier>{30413FCB-C550-4E4B-85F0-F39789145A19}</UniqueIdentifier> + </Filter> + <Filter Include="Resource Files"> + <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml</Extensions> + <UniqueIdentifier>{D54A0D65-9B62-45F4-8B43-F92BC9FF355C}</UniqueIdentifier> + </Filter> + <Filter Include="Driver Files"> + <Extensions>inf;inv;inx;mof;mc;</Extensions> + <UniqueIdentifier>{71F51C61-8117-4556-90E5-DE06697F59D6}</UniqueIdentifier> + </Filter> + </ItemGroup> + <ItemGroup> + <ClCompile Include="filter.c"> + <Filter>Source Files</Filter> + </ClCompile> + </ItemGroup> + <ItemGroup> + <ClInclude Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd"> + <Filter>Header Files</Filter> + </ClInclude> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/osrfx2_DCHU_filter.vcxproj b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/osrfx2_DCHU_filter.vcxproj new file mode 100644 index 00000000..36d85583 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_filter/osrfx2_DCHU_filter.vcxproj @@ -0,0 +1,186 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{3CC42473-D121-41F4-AE26-1F2F0AC65E82}</ProjectGuid> + <RootNamespace>$(MSBuildProjectName)</RootNamespace> + <UMDF_VERSION_MAJOR>2</UMDF_VERSION_MAJOR> + <SupportsPackaging>false</SupportsPackaging> + <RequiresPackageProject>true</RequiresPackageProject> + <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> + <Platform Condition="'$(Platform)' == ''">Win32</Platform> + <SampleGuid>{1A4A32BA-1596-4F52-BC48-B85A6D8D5D12}</SampleGuid> + <WindowsTargetPlatformVersion>10.0.15063.0</WindowsTargetPlatformVersion> + <ProjectName>osrfx2_DCHU_filter</ProjectName> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>False</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType>UMDF</DriverType> + <PlatformToolset>WindowsUserModeDriver10.0</PlatformToolset> + <ConfigurationType>DynamicLibrary</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>True</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType>UMDF</DriverType> + <PlatformToolset>WindowsUserModeDriver10.0</PlatformToolset> + <ConfigurationType>DynamicLibrary</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>False</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType>UMDF</DriverType> + <PlatformToolset>WindowsUserModeDriver10.0</PlatformToolset> + <ConfigurationType>DynamicLibrary</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>True</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType>UMDF</DriverType> + <PlatformToolset>WindowsUserModeDriver10.0</PlatformToolset> + <ConfigurationType>DynamicLibrary</ConfigurationType> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <PropertyGroup> + <OutDir>$(SolutionDir)$(Platform)\$(ConfigurationName)\</OutDir> + </PropertyGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <TargetName>$(ProjectName)</TargetName> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <TargetName>$(ProjectName)</TargetName> + <TargetExt>.dll</TargetExt> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <TargetName>$(ProjectName)</TargetName> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <TargetName>$(ProjectName)</TargetName> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);$(SDK_LIB_PATH)onecore.lib</AdditionalDependencies> + </Link> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + </Midl> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);$(SDK_LIB_PATH)onecore.lib</AdditionalDependencies> + </Link> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + </Midl> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);$(SDK_LIB_PATH)onecore.lib</AdditionalDependencies> + </Link> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + </Midl> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);$(SDK_LIB_PATH)onecore.lib</AdditionalDependencies> + </Link> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\..\inc</AdditionalIncludeDirectories> + </Midl> + </ItemDefinitionGroup> + <ItemGroup> + <ClCompile Include="filter.c" /> + </ItemGroup> + <ItemGroup> + <Inf Exclude="@(Inf)" Include="*.inf" /> + <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + </ItemGroup> + <ItemGroup> + <None Exclude="@(None)" Include="*.txt;*.htm;*.html" /> + <None Exclude="@(None)" Include="*.ico;*.cur;*.bmp;*.dlg;*.rct;*.gif;*.jpg;*.jpeg;*.wav;*.jpe;*.tiff;*.tif;*.png;*.rc2" /> + <None Exclude="@(None)" Include="*.def;*.bat;*.hpj;*.asmx" /> + </ItemGroup> + <ItemGroup> + <ClInclude Exclude="@(ClInclude)" Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd" /> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/dump.c b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/dump.c new file mode 100644 index 00000000..69074bf1 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/dump.c @@ -0,0 +1,444 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + DUMP.C + +Abstract: + + Routines to dump the descriptors information in a human readable form. + +Environment: + + user mode only + +--*/ + +#include <windows.h> +#include <stdio.h> +#include <stdlib.h> +#include "devioctl.h" + +#pragma warning(disable:4200) // +#pragma warning(disable:4201) // nameless struct/union +#pragma warning(disable:4214) // bit field types other than int + +#include <basetyps.h> +#include "usbdi.h" +#include "public.h" + +#pragma warning(default:4200) +#pragma warning(default:4201) +#pragma warning(default:4214) + +HANDLE +OpenDevice( + _In_ BOOL Synchronous + ); + + +char* +usbDescriptorTypeString(UCHAR bDescriptorType ) +/*++ +Routine Description: + + Called to get ascii string of USB descriptor + +Arguments: + + PUSB_ENDPOINT_DESCRIPTOR->bDescriptorType or + PUSB_DEVICE_DESCRIPTOR->bDescriptorType or + PUSB_INTERFACE_DESCRIPTOR->bDescriptorType or + PUSB_STRING_DESCRIPTOR->bDescriptorType or + PUSB_POWER_DESCRIPTOR->bDescriptorType or + PUSB_CONFIGURATION_DESCRIPTOR->bDescriptorType + +Return Value: + + ptr to string + +--*/ +{ + + switch(bDescriptorType) { + + case USB_DEVICE_DESCRIPTOR_TYPE: + return "USB_DEVICE_DESCRIPTOR_TYPE"; + + case USB_CONFIGURATION_DESCRIPTOR_TYPE: + return "USB_CONFIGURATION_DESCRIPTOR_TYPE"; + + + case USB_STRING_DESCRIPTOR_TYPE: + return "USB_STRING_DESCRIPTOR_TYPE"; + + + case USB_INTERFACE_DESCRIPTOR_TYPE: + return "USB_INTERFACE_DESCRIPTOR_TYPE"; + + + case USB_ENDPOINT_DESCRIPTOR_TYPE: + return "USB_ENDPOINT_DESCRIPTOR_TYPE"; + + +#ifdef USB_POWER_DESCRIPTOR_TYPE // this is the older definintion which is actually obsolete + // workaround for temporary bug in 98ddk, older USB100.h file + case USB_POWER_DESCRIPTOR_TYPE: + return "USB_POWER_DESCRIPTOR_TYPE"; +#endif + +#ifdef USB_RESERVED_DESCRIPTOR_TYPE // this is the current version of USB100.h as in NT5DDK + + case USB_RESERVED_DESCRIPTOR_TYPE: + return "USB_RESERVED_DESCRIPTOR_TYPE"; + + case USB_CONFIG_POWER_DESCRIPTOR_TYPE: + return "USB_CONFIG_POWER_DESCRIPTOR_TYPE"; + + case USB_INTERFACE_POWER_DESCRIPTOR_TYPE: + return "USB_INTERFACE_POWER_DESCRIPTOR_TYPE"; +#endif // for current nt5ddk version of USB100.h + + default: + return "??? UNKNOWN!!"; + } +} + + +char * +usbEndPointTypeString(UCHAR bmAttributes) +/*++ +Routine Description: + + Called to get ascii string of endpt descriptor type + +Arguments: + + PUSB_ENDPOINT_DESCRIPTOR->bmAttributes + +Return Value: + + ptr to string + +--*/ +{ + UINT typ = bmAttributes & USB_ENDPOINT_TYPE_MASK; + + + switch( typ) { + case USB_ENDPOINT_TYPE_INTERRUPT: + return "USB_ENDPOINT_TYPE_INTERRUPT"; + + case USB_ENDPOINT_TYPE_BULK: + return "USB_ENDPOINT_TYPE_BULK"; + + case USB_ENDPOINT_TYPE_ISOCHRONOUS: + return "USB_ENDPOINT_TYPE_ISOCHRONOUS"; + + case USB_ENDPOINT_TYPE_CONTROL: + return "USB_ENDPOINT_TYPE_CONTROL"; + + default: + return "??? UNKNOWN!!"; + } +} + + +char * +usbConfigAttributesString(UCHAR bmAttributes) +/*++ +Routine Description: + + Called to get ascii string of USB_CONFIGURATION_DESCRIPTOR attributes + +Arguments: + + PUSB_CONFIGURATION_DESCRIPTOR->bmAttributes + +Return Value: + + ptr to string + +--*/ +{ + UINT typ = bmAttributes & USB_CONFIG_POWERED_MASK; + + + switch( typ) { + + case USB_CONFIG_BUS_POWERED: + return "USB_CONFIG_BUS_POWERED"; + + case USB_CONFIG_SELF_POWERED: + return "USB_CONFIG_SELF_POWERED"; + + case USB_CONFIG_REMOTE_WAKEUP: + return "USB_CONFIG_REMOTE_WAKEUP"; + + + default: + return "??? UNKNOWN!!"; + } +} + + +void +print_USB_CONFIGURATION_DESCRIPTOR(PUSB_CONFIGURATION_DESCRIPTOR cd) +/*++ +Routine Description: + + Called to do formatted ascii dump to console of a USB config descriptor + +Arguments: + + ptr to USB configuration descriptor + +Return Value: + + none + +--*/ +{ + printf("\n===================\nUSB_CONFIGURATION_DESCRIPTOR\n"); + + printf( + "bLength = 0x%x, decimal %d\n", cd->bLength, cd->bLength + ); + + printf( + "bDescriptorType = 0x%x ( %s )\n", cd->bDescriptorType, + usbDescriptorTypeString( cd->bDescriptorType ) + ); + + printf( + "wTotalLength = 0x%x, decimal %d\n", cd->wTotalLength, cd->wTotalLength + ); + + printf( + "bNumInterfaces = 0x%x, decimal %d\n", cd->bNumInterfaces, cd->bNumInterfaces + ); + + printf( + "bConfigurationValue = 0x%x, decimal %d\n", + cd->bConfigurationValue, cd->bConfigurationValue + ); + + printf( + "iConfiguration = 0x%x, decimal %d\n", cd->iConfiguration, cd->iConfiguration + ); + + printf( + "bmAttributes = 0x%x ( %s )\n", cd->bmAttributes, + usbConfigAttributesString( cd->bmAttributes ) + ); + + printf( + "MaxPower = 0x%x, decimal %d\n", cd->MaxPower, cd->MaxPower + ); +} + + +void +print_USB_INTERFACE_DESCRIPTOR(PUSB_INTERFACE_DESCRIPTOR id, UINT ix) +/*++ +Routine Description: + + Called to do formatted ascii dump to console of a USB interface descriptor + +Arguments: + + ptr to USB interface descriptor + +Return Value: + + none + +--*/ +{ + printf("\n-----------------------------\nUSB_INTERFACE_DESCRIPTOR #%d\n", ix); + + + printf( + "bLength = 0x%x\n", id->bLength + ); + + + printf( + "bDescriptorType = 0x%x ( %s )\n", id->bDescriptorType, + usbDescriptorTypeString( id->bDescriptorType ) + ); + + + printf( + "bInterfaceNumber = 0x%x\n", id->bInterfaceNumber + ); + printf( + "bAlternateSetting = 0x%x\n", id->bAlternateSetting + ); + printf( + "bNumEndpoints = 0x%x\n", id->bNumEndpoints + ); + printf( + "bInterfaceClass = 0x%x\n", id->bInterfaceClass + ); + printf( + "bInterfaceSubClass = 0x%x\n", id->bInterfaceSubClass + ); + printf( + "bInterfaceProtocol = 0x%x\n", id->bInterfaceProtocol + ); + printf( + "bInterface = 0x%x\n", id->iInterface + ); +} + + +void +print_USB_ENDPOINT_DESCRIPTOR(PUSB_ENDPOINT_DESCRIPTOR ed, int i) +/*++ +Routine Description: + + Called to do formatted ascii dump to console of a USB endpoint descriptor + +Arguments: + + ptr to USB endpoint descriptor, + index of this endpt in interface desc + +Return Value: + + none + +--*/ +{ + printf( + "------------------------------\nUSB_ENDPOINT_DESCRIPTOR for Pipe%02d\n", i + ); + + printf( + "bLength = 0x%x\n", ed->bLength + ); + + printf( + "bDescriptorType = 0x%x ( %s )\n", ed->bDescriptorType, + usbDescriptorTypeString( ed->bDescriptorType ) + ); + + if ( USB_ENDPOINT_DIRECTION_IN( ed->bEndpointAddress ) ) { + printf( + "bEndpointAddress= 0x%x ( INPUT )\n", ed->bEndpointAddress + ); + } else { + printf( + "bEndpointAddress= 0x%x ( OUTPUT )\n", ed->bEndpointAddress + ); + } + + printf( + "bmAttributes= 0x%x ( %s )\n", ed->bmAttributes, + usbEndPointTypeString ( ed->bmAttributes ) + ); + + printf( + "wMaxPacketSize= 0x%x, decimal %d\n", ed->wMaxPacketSize, + ed->wMaxPacketSize + ); + + printf( + "bInterval = 0x%x, decimal %d\n", ed->bInterval, ed->bInterval + ); +} + + +BOOL +DumpUsbConfig() +/*++ +Routine Description: + + Called to do formatted ascii dump to console of USB + configuration, interface, and endpoint descriptors. + +Arguments: + + none + +Return Value: + + TRUE or FALSE + +--*/ +{ + HANDLE hDev; + UINT success; + int siz, nBytes; + char buf[256] = {'\0'}; + + hDev = OpenDevice(TRUE); + if(hDev == INVALID_HANDLE_VALUE) + { + return FALSE; + } + + siz = sizeof(buf); + + success = DeviceIoControl(hDev, + IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR, + buf, + siz, + buf, + siz, + (PULONG) &nBytes, + NULL); + + if(success == FALSE) { + printf("Ioct - GetConfigDesc failed %d\n", GetLastError()); + } else { + + ULONG i; + UINT j, n; + char *pch; + PUSB_CONFIGURATION_DESCRIPTOR cd; + PUSB_INTERFACE_DESCRIPTOR id; + PUSB_ENDPOINT_DESCRIPTOR ed; + + pch = buf; + n = 0; + + cd = (PUSB_CONFIGURATION_DESCRIPTOR) pch; + + print_USB_CONFIGURATION_DESCRIPTOR( cd ); + + pch += cd->bLength; + + do { + id = (PUSB_INTERFACE_DESCRIPTOR) pch; + + print_USB_INTERFACE_DESCRIPTOR(id, n++); + + pch += id->bLength; + for (j=0; j<id->bNumEndpoints; j++) { + + ed = (PUSB_ENDPOINT_DESCRIPTOR) pch; + + print_USB_ENDPOINT_DESCRIPTOR(ed,j); + + pch += ed->bLength; + } + i = (ULONG)(pch - buf); + + } while (i<cd->wTotalLength); + } + + CloseHandle(hDev); + + return success; + +} + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/osrfx2_DCHU_testapp.Filters b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/osrfx2_DCHU_testapp.Filters new file mode 100644 index 00000000..f9efc3e3 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/osrfx2_DCHU_testapp.Filters @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Source Files"> + <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;*</Extensions> + <UniqueIdentifier>{D5BFAD22-1AD2-44F8-AC33-05C04A9C26D9}</UniqueIdentifier> + </Filter> + <Filter Include="Header Files"> + <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> + <UniqueIdentifier>{14E678C7-EAC3-42F6-9F4B-2CDD17427D73}</UniqueIdentifier> + </Filter> + <Filter Include="Resource Files"> + <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml</Extensions> + <UniqueIdentifier>{CEE0A75C-90B6-472A-8FC1-9375F1EAD2C9}</UniqueIdentifier> + </Filter> + </ItemGroup> + <ItemGroup> + <ClCompile Include="dump.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="testapp.c"> + <Filter>Source Files</Filter> + </ClCompile> + </ItemGroup> + <ItemGroup> + <ResourceCompile Include="testapp.rc"> + <Filter>Resource Files</Filter> + </ResourceCompile> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/osrfx2_DCHU_testapp.vcxproj b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/osrfx2_DCHU_testapp.vcxproj new file mode 100644 index 00000000..49932df1 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/osrfx2_DCHU_testapp.vcxproj @@ -0,0 +1,193 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{6EED5CDD-5526-40DC-97F9-582857E10187}</ProjectGuid> + <RootNamespace>$(MSBuildProjectName)</RootNamespace> + <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> + <Platform Condition="'$(Platform)' == ''">Win32</Platform> + <SampleGuid>{F19E45AF-8B05-4204-A66B-9BDBFE333233}</SampleGuid> + <ProjectName>osrfx2_DCHU_testapp</ProjectName> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>False</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType /> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> + <ConfigurationType>Application</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>True</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType /> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> + <ConfigurationType>Application</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>False</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType /> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> + <ConfigurationType>Application</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>True</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType /> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> + <ConfigurationType>Application</ConfigurationType> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <PropertyGroup> + <OutDir>$(IntDir)</OutDir> + </PropertyGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ItemGroup Label="WrappedTaskItems" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <TargetName>osrusbfx2</TargetName> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <TargetName>osrusbfx2</TargetName> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <TargetName>osrusbfx2</TargetName> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <TargetName>osrusbfx2</TargetName> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);onecore.lib</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);onecore.lib</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);onecore.lib</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);onecore.lib</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemGroup> + <ClCompile Include="dump.c" /> + <ClCompile Include="testapp.c" /> + <ResourceCompile Include="testapp.rc" /> + </ItemGroup> + <ItemGroup> + <Inf Exclude="@(Inf)" Include="*.inf" /> + <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'" /> + </ItemGroup> + <ItemGroup> + <None Exclude="@(None)" Include="*.txt;*.htm;*.html" /> + <None Exclude="@(None)" Include="*.ico;*.cur;*.bmp;*.dlg;*.rct;*.gif;*.jpg;*.jpeg;*.wav;*.jpe;*.tiff;*.tif;*.png;*.rc2" /> + <None Exclude="@(None)" Include="*.def;*.bat;*.hpj;*.asmx" /> + </ItemGroup> + <ItemGroup> + <ClInclude Exclude="@(ClInclude)" Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd" /> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/osrusbfx2.vcxproj b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/osrusbfx2.vcxproj new file mode 100644 index 00000000..225dcde2 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/osrusbfx2.vcxproj @@ -0,0 +1,194 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{6EED5CDD-5526-40DC-97F9-582857E10187}</ProjectGuid> + <RootNamespace>$(MSBuildProjectName)</RootNamespace> + <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> + <Platform Condition="'$(Platform)' == ''">Win32</Platform> + <SampleGuid>{F19E45AF-8B05-4204-A66B-9BDBFE333233}</SampleGuid> + <ProjectName>osrfx2_DCHU_testapp</ProjectName> + <WindowsTargetPlatformVersion>10.0.15063.0</WindowsTargetPlatformVersion> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>False</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType /> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> + <ConfigurationType>Application</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>True</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType /> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> + <ConfigurationType>Application</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>False</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType /> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> + <ConfigurationType>Application</ConfigurationType> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>True</UseDebugLibraries> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <DriverType /> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> + <ConfigurationType>Application</ConfigurationType> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <PropertyGroup> + <OutDir>$(IntDir)</OutDir> + </PropertyGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" /> + </ImportGroup> + <ItemGroup Label="WrappedTaskItems" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <TargetName>osrfx2_DCHU_testapp</TargetName> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <TargetName>osrfx2_DCHU_testapp</TargetName> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <TargetName>osrfx2_DCHU_testapp</TargetName> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <TargetName>osrfx2_DCHU_testapp</TargetName> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);onecore.lib</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);onecore.lib</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);onecore.lib</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <TreatWarningAsError>true</TreatWarningAsError> + <WarningLevel>Level4</WarningLevel> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + <ExceptionHandling> + </ExceptionHandling> + </ClCompile> + <ResourceCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </ResourceCompile> + <Midl> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH);..\inc;..\sys\inc</AdditionalIncludeDirectories> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> + </Midl> + <Link> + <AdditionalDependencies>%(AdditionalDependencies);onecore.lib</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemGroup> + <ClCompile Include="dump.c" /> + <ClCompile Include="testapp.c" /> + <ResourceCompile Include="testapp.rc" /> + </ItemGroup> + <ItemGroup> + <Inf Exclude="@(Inf)" Include="*.inf" /> + <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'" /> + </ItemGroup> + <ItemGroup> + <None Exclude="@(None)" Include="*.txt;*.htm;*.html" /> + <None Exclude="@(None)" Include="*.ico;*.cur;*.bmp;*.dlg;*.rct;*.gif;*.jpg;*.jpeg;*.wav;*.jpe;*.tiff;*.tif;*.png;*.rc2" /> + <None Exclude="@(None)" Include="*.def;*.bat;*.hpj;*.asmx" /> + </ItemGroup> + <ItemGroup> + <ClInclude Exclude="@(ClInclude)" Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd" /> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/test.cmd b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/test.cmd new file mode 100644 index 00000000..30b18b85 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/test.cmd @@ -0,0 +1,6 @@ +FOR /L %%i IN (0,1,100000) do ( + + osrusbfx2.exe -r 512 -w 512 -c 1000000 -v + +) + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/testapp.c b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/testapp.c new file mode 100644 index 00000000..455c2bbe --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/testapp.c @@ -0,0 +1,1214 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + testapp.c + +Abstract: + + Console test app for Osr Fx2 Learning Kit. + +Environment: + + user mode only + +--*/ + + +#include <DriverSpecs.h> +_Analysis_mode_(_Analysis_code_type_user_code_) + +#include <windows.h> +#include <stdio.h> +#include <stdlib.h> +#include <assert.h> + +#include "devioctl.h" +#include "strsafe.h" + +#pragma warning(disable:4200) // +#pragma warning(disable:4201) // nameless struct/union +#pragma warning(disable:4214) // bit field types other than int + +#include <cfgmgr32.h> +#include <basetyps.h> +#include "usbdi.h" +#include "public.h" + +#pragma warning(default:4200) +#pragma warning(default:4201) +#pragma warning(default:4214) + +#define WHILE(a) \ +while(__pragma(warning(disable:4127)) a __pragma(warning(disable:4127))) + +#define MAX_DEVPATH_LENGTH 256 +#define NUM_ASYNCH_IO 100 +#define BUFFER_SIZE 1024 +#define READER_TYPE 1 +#define WRITER_TYPE 2 + +BOOL G_fDumpUsbConfig = FALSE; // flags set in response to console command line switches +BOOL G_fDumpReadData = FALSE; +BOOL G_fRead = FALSE; +BOOL G_fWrite = FALSE; +BOOL G_fPlayWithDevice = FALSE; +BOOL G_fPerformAsyncIo = FALSE; +ULONG G_IterationCount = 1; //count of iterations of the test we are to perform +ULONG G_WriteLen = 512; // #bytes to write +ULONG G_ReadLen = 512; // #bytes to read + +BOOL +DumpUsbConfig( // defined in dump.c + ); + +typedef enum _INPUT_FUNCTION { + LIGHT_ONE_BAR = 1, + CLEAR_ONE_BAR, + LIGHT_ALL_BARS, + CLEAR_ALL_BARS, + GET_BAR_GRAPH_LIGHT_STATE, + GET_SWITCH_STATE, + GET_SWITCH_STATE_AS_INTERRUPT_MESSAGE, + GET_7_SEGEMENT_STATE, + SET_7_SEGEMENT_STATE, + RESET_DEVICE, + REENUMERATE_DEVICE, +} INPUT_FUNCTION; + +_Success_(return) +BOOL +GetDevicePath( + _In_ LPGUID InterfaceGuid, + _Out_writes_z_(BufLen) PWCHAR DevicePath, + _In_ size_t BufLen + ) +{ + CONFIGRET cr = CR_SUCCESS; + PWSTR deviceInterfaceList = NULL; + ULONG deviceInterfaceListLength = 0; + PWSTR nextInterface; + HRESULT hr = E_FAIL; + BOOL bRet = TRUE; + + cr = CM_Get_Device_Interface_List_Size( + &deviceInterfaceListLength, + InterfaceGuid, + NULL, + CM_GET_DEVICE_INTERFACE_LIST_PRESENT); + if (cr != CR_SUCCESS) { + printf("Error 0x%x retrieving device interface list size.\n", cr); + goto clean0; + } + + if (deviceInterfaceListLength <= 1) { + bRet = FALSE; + printf("Error: No active device interfaces found.\n" + " Is the sample driver loaded?"); + goto clean0; + } + + deviceInterfaceList = (PWSTR)malloc(deviceInterfaceListLength * sizeof(WCHAR)); + if (deviceInterfaceList == NULL) { + bRet = FALSE; + printf("Error allocating memory for device interface list.\n"); + goto clean0; + } + ZeroMemory(deviceInterfaceList, deviceInterfaceListLength * sizeof(WCHAR)); + + cr = CM_Get_Device_Interface_List( + InterfaceGuid, + NULL, + deviceInterfaceList, + deviceInterfaceListLength, + CM_GET_DEVICE_INTERFACE_LIST_PRESENT); + if (cr != CR_SUCCESS) { + printf("Error 0x%x retrieving device interface list.\n", cr); + goto clean0; + } + + nextInterface = deviceInterfaceList + wcslen(deviceInterfaceList) + 1; + if (*nextInterface != UNICODE_NULL) { + printf("Warning: More than one device interface instance found. \n" + "Selecting first matching device.\n\n"); + } + + hr = StringCchCopy(DevicePath, BufLen, deviceInterfaceList); + if (FAILED(hr)) { + bRet = FALSE; + printf("Error: StringCchCopy failed with HRESULT 0x%x", hr); + goto clean0; + } + +clean0: + if (deviceInterfaceList != NULL) { + free(deviceInterfaceList); + } + if (CR_SUCCESS != cr) { + bRet = FALSE; + } + + return bRet; +} + +_Check_return_ +_Ret_notnull_ +_Success_(return != INVALID_HANDLE_VALUE) +HANDLE +OpenDevice( + _In_ BOOL Synchronous + ) + +/*++ +Routine Description: + + Called by main() to open an instance of our device after obtaining its name + +Arguments: + + Synchronous - TRUE, if Device is to be opened for synchronous access. + FALSE, otherwise. + +Return Value: + + Device handle on success else INVALID_HANDLE_VALUE + +--*/ + +{ + HANDLE hDev; + WCHAR completeDeviceName[MAX_DEVPATH_LENGTH]; + + if ( !GetDevicePath( + (LPGUID) &GUID_DEVINTERFACE_OSRUSBFX2, + completeDeviceName, + sizeof(completeDeviceName)/sizeof(completeDeviceName[0])) ) + { + return INVALID_HANDLE_VALUE; + } + + printf("DeviceName = (%S)\n", completeDeviceName); + + if(Synchronous) { + hDev = CreateFile(completeDeviceName, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_WRITE | FILE_SHARE_READ, + NULL, // default security + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + } else { + + hDev = CreateFile(completeDeviceName, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_WRITE | FILE_SHARE_READ, + NULL, // default security + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, + NULL); + } + + if (hDev == INVALID_HANDLE_VALUE) { + printf("Failed to open the device, error - %d", GetLastError()); + } else { + printf("Opened the device successfully.\n"); + } + + return hDev; +} + + + +VOID +Usage() + +/*++ +Routine Description: + + Called by main() to dump usage info to the console when + the app is called with no parms or with an invalid parm + +Arguments: + + None + +Return Value: + + None + +--*/ + +{ + printf("Usage for osrusbfx2 testapp:\n"); + printf("-r [n] where n is number of bytes to read\n"); + printf("-w [n] where n is number of bytes to write\n"); + printf("-c [n] where n is number of iterations (default = 1)\n"); + printf("-v verbose -- dumps read data\n"); + printf("-p to control bar LEDs, seven segment, and dip switch\n"); + printf("-a to perform asynchronous I/O\n"); + printf("-u to dump USB configuration and pipe info \n"); + + return; +} + + +void +Parse( + _In_ int argc, + _In_reads_(argc) LPSTR *argv + ) + +/*++ +Routine Description: + + Called by main() to parse command line parms + +Arguments: + + argc and argv that was passed to main() + +Return Value: + + Sets global flags as per user function request + +--*/ + +{ + int i; + + if ( argc < 2 ) // give usage if invoked with no parms + Usage(); + + for (i=0; i<argc; i++) { + if (argv[i][0] == '-' || + argv[i][0] == '/') { + switch(argv[i][1]) { + case 'r': + case 'R': + if (i+1 >= argc) { + Usage(); + exit(1); + } + else { +#pragma warning(suppress: 6385) + G_ReadLen = atoi(&argv[i+1][0]); + G_fRead = TRUE; + } + i++; + break; + case 'w': + case 'W': + if (i+1 >= argc) { + Usage(); + exit(1); + } + else { + G_WriteLen = atoi(&argv[i+1][0]); + G_fWrite = TRUE; + } + i++; + break; + case 'c': + case 'C': + if (i+1 >= argc) { + Usage(); + exit(1); + } + else { + G_IterationCount = atoi(&argv[i+1][0]); + } + i++; + break; + case 'u': + case 'U': + G_fDumpUsbConfig = TRUE; + break; + case 'p': + case 'P': + G_fPlayWithDevice = TRUE; + break; + case 'a': + case 'A': + G_fPerformAsyncIo = TRUE; + break; + case 'v': + case 'V': + G_fDumpReadData = TRUE; + break; + default: + Usage(); + } + } + } +} + +BOOL +Compare_Buffs( + _In_reads_bytes_(buff1length) char *buff1, + _In_ ULONG buff1length, + _In_reads_bytes_(buff2length) char *buff2, + _In_ ULONG buff2length + ) +/*++ +Routine Description: + + Called to verify read and write buffers match for loopback test + +Arguments: + + buffers to compare and length + +Return Value: + + TRUE if buffers match, else FALSE + +--*/ +{ + int ok = 1; + + if (buff1length != buff2length || memcmp(buff1, buff2, buff1length )) { + // Edi, and Esi point to the mismatching char and ecx indicates the + // remaining length. + ok = 0; + } + + return ok; +} + +#define NPERLN 8 + +VOID +Dump( + UCHAR *b, + int len +) + +/*++ +Routine Description: + + Called to do formatted ascii dump to console of the io buffer + +Arguments: + + buffer and length + +Return Value: + + none + +--*/ + +{ + ULONG i; + ULONG longLen = (ULONG)len / sizeof( ULONG ); + PULONG pBuf = (PULONG) b; + + // dump an ordinal ULONG for each sizeof(ULONG)'th byte + printf("\n****** BEGIN DUMP LEN decimal %d, 0x%x\n", len,len); + for (i=0; i<longLen; i++) { + printf("%04X ", *pBuf++); + if (i % NPERLN == (NPERLN - 1)) { + printf("\n"); + } + } + if (i % NPERLN != 0) { + printf("\n"); + } + printf("\n****** END DUMP LEN decimal %d, 0x%x\n", len,len); +} + + +BOOL +PlayWithDevice() +{ + HANDLE deviceHandle; + DWORD code; + ULONG index; + INPUT_FUNCTION function; + BAR_GRAPH_STATE barGraphState; + ULONG bar; + SWITCH_STATE switchState; + UCHAR sevenSegment = 0; + UCHAR i; + BOOL result = FALSE; + + deviceHandle = OpenDevice(FALSE); + + if (deviceHandle == INVALID_HANDLE_VALUE) { + + printf("Unable to find any OSR FX2 devices!\n"); + + return FALSE; + + } + + // + // Infinitely print out the list of choices, ask for input, process + // the request + // + WHILE(TRUE) { + + printf ("\nUSBFX TEST -- Functions:\n\n"); + printf ("\t1. Light Bar\n"); + printf ("\t2. Clear Bar\n"); + printf ("\t3. Light entire Bar graph\n"); + printf ("\t4. Clear entire Bar graph\n"); + printf ("\t5. Get bar graph state\n"); + printf ("\t6. Get Switch state\n"); + printf ("\t7. Get Switch Interrupt Message\n"); + printf ("\t8. Get 7 segment state\n"); + printf ("\t9. Set 7 segment state\n"); + printf ("\t10. Reset the device\n"); + printf ("\t11. Reenumerate the device\n"); + printf ("\n\t0. Exit\n"); + printf ("\n\tSelection: "); + + if (scanf_s ("%d", &function) <= 0) { + + printf("Error reading input!\n"); + goto Error; + + } + + switch(function) { + + case LIGHT_ONE_BAR: + + printf("Which Bar (input number 1 thru 8)?\n"); + if (scanf_s ("%d", &bar) <= 0) { + + printf("Error reading input!\n"); + goto Error; + + } + + if(bar == 0 || bar > 8){ + printf("Invalid bar number!\n"); + goto Error; + } + + bar--; // normalize to 0 to 7 + + barGraphState.BarsAsUChar = 1 << (UCHAR)bar; + + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, + &barGraphState, // Ptr to InBuffer + sizeof(BAR_GRAPH_STATE), // Length of InBuffer + NULL, // Ptr to OutBuffer + 0, // Length of OutBuffer + &index, // BytesReturned + 0)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + } + + break; + + case CLEAR_ONE_BAR: + + + printf("Which Bar (input number 1 thru 8)?\n"); + if (scanf_s ("%d", &bar) <= 0) { + + printf("Error reading input!\n"); + goto Error; + + } + + if(bar == 0 || bar > 8){ + printf("Invalid bar number!\n"); + goto Error; + } + + bar--; + + // + // Read the current state + // + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY, + NULL, // Ptr to InBuffer + 0, // Length of InBuffer + &barGraphState, // Ptr to OutBuffer + sizeof(BAR_GRAPH_STATE), // Length of OutBuffer + &index, // BytesReturned + 0)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + } + + if (barGraphState.BarsAsUChar & (1 << bar)) { + + printf("Bar is set...Clearing it\n"); + barGraphState.BarsAsUChar &= ~(1 << bar); + + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, + &barGraphState, // Ptr to InBuffer + sizeof(BAR_GRAPH_STATE), // Length of InBuffer + NULL, // Ptr to OutBuffer + 0, // Length of OutBuffer + &index, // BytesReturned + 0)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + + } + + } else { + + printf("Bar not set.\n"); + + } + + break; + + case LIGHT_ALL_BARS: + + barGraphState.BarsAsUChar = 0xFF; + + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, + &barGraphState, // Ptr to InBuffer + sizeof(BAR_GRAPH_STATE), // Length of InBuffer + NULL, // Ptr to OutBuffer + 0, // Length of OutBuffer + &index, // BytesReturned + 0)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + } + + break; + + case CLEAR_ALL_BARS: + + barGraphState.BarsAsUChar = 0; + + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, + &barGraphState, // Ptr to InBuffer + sizeof(BAR_GRAPH_STATE), // Length of InBuffer + NULL, // Ptr to OutBuffer + 0, // Length of OutBuffer + &index, // BytesReturned + 0)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + } + + break; + + + case GET_BAR_GRAPH_LIGHT_STATE: + + barGraphState.BarsAsUChar = 0; + + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY, + NULL, // Ptr to InBuffer + 0, // Length of InBuffer + &barGraphState, // Ptr to OutBuffer + sizeof(BAR_GRAPH_STATE), // Length of OutBuffer + &index, // BytesReturned + 0)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + } + + printf("Bar Graph: \n"); + printf(" Bar8 is %s\n", barGraphState.Bar8 ? "ON" : "OFF"); + printf(" Bar7 is %s\n", barGraphState.Bar7 ? "ON" : "OFF"); + printf(" Bar6 is %s\n", barGraphState.Bar6 ? "ON" : "OFF"); + printf(" Bar5 is %s\n", barGraphState.Bar5 ? "ON" : "OFF"); + printf(" Bar4 is %s\n", barGraphState.Bar4 ? "ON" : "OFF"); + printf(" Bar3 is %s\n", barGraphState.Bar3 ? "ON" : "OFF"); + printf(" Bar2 is %s\n", barGraphState.Bar2 ? "ON" : "OFF"); + printf(" Bar1 is %s\n", barGraphState.Bar1 ? "ON" : "OFF"); + + break; + + case GET_SWITCH_STATE: + + switchState.SwitchesAsUChar = 0; + + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_READ_SWITCHES, + NULL, // Ptr to InBuffer + 0, // Length of InBuffer + &switchState, // Ptr to OutBuffer + sizeof(SWITCH_STATE), // Length of OutBuffer + &index, // BytesReturned + 0)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + } + + printf("Switches: \n"); + printf(" Switch8 is %s\n", switchState.Switch8 ? "ON" : "OFF"); + printf(" Switch7 is %s\n", switchState.Switch7 ? "ON" : "OFF"); + printf(" Switch6 is %s\n", switchState.Switch6 ? "ON" : "OFF"); + printf(" Switch5 is %s\n", switchState.Switch5 ? "ON" : "OFF"); + printf(" Switch4 is %s\n", switchState.Switch4 ? "ON" : "OFF"); + printf(" Switch3 is %s\n", switchState.Switch3 ? "ON" : "OFF"); + printf(" Switch2 is %s\n", switchState.Switch2 ? "ON" : "OFF"); + printf(" Switch1 is %s\n", switchState.Switch1 ? "ON" : "OFF"); + + break; + + case GET_SWITCH_STATE_AS_INTERRUPT_MESSAGE: + + switchState.SwitchesAsUChar = 0; + + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE, + NULL, // Ptr to InBuffer + 0, // Length of InBuffer + &switchState, // Ptr to OutBuffer + sizeof(switchState), // Length of OutBuffer + &index, // BytesReturned + 0)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + } + + printf("Switches: %d\n",index); + printf(" Switch8 is %s\n", switchState.Switch8 ? "ON" : "OFF"); + printf(" Switch7 is %s\n", switchState.Switch7 ? "ON" : "OFF"); + printf(" Switch6 is %s\n", switchState.Switch6 ? "ON" : "OFF"); + printf(" Switch5 is %s\n", switchState.Switch5 ? "ON" : "OFF"); + printf(" Switch4 is %s\n", switchState.Switch4 ? "ON" : "OFF"); + printf(" Switch3 is %s\n", switchState.Switch3 ? "ON" : "OFF"); + printf(" Switch2 is %s\n", switchState.Switch2 ? "ON" : "OFF"); + printf(" Switch1 is %s\n", switchState.Switch1 ? "ON" : "OFF"); + + break; + + case GET_7_SEGEMENT_STATE: + + sevenSegment = 0; + + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY, + NULL, // Ptr to InBuffer + 0, // Length of InBuffer + &sevenSegment, // Ptr to OutBuffer + sizeof(UCHAR), // Length of OutBuffer + &index, // BytesReturned + 0)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + } + + printf("7 Segment mask: 0x%x\n", sevenSegment); + break; + + case SET_7_SEGEMENT_STATE: + + for (i = 0; i < 8; i++) { + + sevenSegment = 1 << i; + + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY, + &sevenSegment, // Ptr to InBuffer + sizeof(UCHAR), // Length of InBuffer + NULL, // Ptr to OutBuffer + 0, // Length of OutBuffer + &index, // BytesReturned + 0)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + } + + printf("This is %d\n", i); + Sleep(500); + + } + + printf("7 Segment mask: 0x%x\n", sevenSegment); + break; + + case RESET_DEVICE: + + printf("Reset the device\n"); + + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_RESET_DEVICE, + NULL, // Ptr to InBuffer + 0, // Length of InBuffer + NULL, // Ptr to OutBuffer + 0, // Length of OutBuffer + &index, // BytesReturned + NULL)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + } + + break; + + case REENUMERATE_DEVICE: + + printf("Re-enumerate the device\n"); + + if (!DeviceIoControl(deviceHandle, + IOCTL_OSRUSBFX2_REENUMERATE_DEVICE, + NULL, // Ptr to InBuffer + 0, // Length of InBuffer + NULL, // Ptr to OutBuffer + 0, // Length of OutBuffer + &index, // BytesReturned + NULL)) { // Ptr to Overlapped structure + + code = GetLastError(); + + printf("DeviceIoControl failed with error 0x%x\n", code); + + goto Error; + } + + // + // Close the handle to the device and exit out so that + // the driver can unload when the device is surprise-removed + // and reenumerated. + // + default: + + result = TRUE; + goto Error; + + } + + } // end of while loop + +Error: + + CloseHandle(deviceHandle); + return result; + +} + + +ULONG +AsyncIo( + PVOID ThreadParameter + ) +{ + HANDLE hDevice = INVALID_HANDLE_VALUE; + HANDLE hCompletionPort = NULL; + OVERLAPPED *pOvList = NULL; + PUCHAR buf = NULL; + ULONG_PTR i; + ULONG ioType = (ULONG)(ULONG_PTR)ThreadParameter; + ULONG error; + + hDevice = OpenDevice(FALSE); + + if (hDevice == INVALID_HANDLE_VALUE) { + printf("Cannot open device %d\n", GetLastError()); + goto Error; + } + + hCompletionPort = CreateIoCompletionPort(hDevice, NULL, 1, 0); + + if (hCompletionPort == NULL) { + printf("Cannot open completion port %d \n",GetLastError()); + goto Error; + } + + pOvList = (OVERLAPPED *)malloc(NUM_ASYNCH_IO * sizeof(OVERLAPPED)); + + if (pOvList == NULL) { + printf("Cannot allocate overlapped array \n"); + goto Error; + } + + buf = (PUCHAR)malloc(NUM_ASYNCH_IO * BUFFER_SIZE); + + if (buf == NULL) { + printf("Cannot allocate buffer \n"); + goto Error; + } + + ZeroMemory(pOvList, NUM_ASYNCH_IO * sizeof(OVERLAPPED)); + ZeroMemory(buf, NUM_ASYNCH_IO * BUFFER_SIZE); + + // + // Issue asynch I/O + // + + for (i = 0; i < NUM_ASYNCH_IO; i++) { + if (ioType == READER_TYPE) { + if ( ReadFile( hDevice, + buf + (i* BUFFER_SIZE), + BUFFER_SIZE, + NULL, + &pOvList[i]) == 0) { + + error = GetLastError(); + if (error != ERROR_IO_PENDING) { + printf(" %Iu th read failed %d \n",i, GetLastError()); + goto Error; + } + } + + } else { + if ( WriteFile( hDevice, + buf + (i* BUFFER_SIZE), + BUFFER_SIZE, + NULL, + &pOvList[i]) == 0) { + error = GetLastError(); + if (error != ERROR_IO_PENDING) { + printf(" %Iu th write failed %d \n",i, GetLastError()); + goto Error; + } + } + } + } + + // + // Wait for the I/Os to complete. If one completes then reissue the I/O + // + + WHILE (1) { + OVERLAPPED *completedOv; + ULONG_PTR key; + ULONG numberOfBytesTransferred; + + if ( GetQueuedCompletionStatus(hCompletionPort, &numberOfBytesTransferred, + &key, &completedOv, INFINITE) == 0) { + printf("GetQueuedCompletionStatus failed %d\n", GetLastError()); + goto Error; + } + + // + // Read successfully completed. Issue another one. + // + + if (ioType == READER_TYPE) { + + i = completedOv - pOvList; + + printf("Number of bytes read by request number %Iu is %d\n", + i, numberOfBytesTransferred); + + if ( ReadFile( hDevice, + buf + (i * BUFFER_SIZE), + BUFFER_SIZE, + NULL, + completedOv) == 0) { + error = GetLastError(); + if (error != ERROR_IO_PENDING) { + printf("%Iu th Read failed %d \n", i, GetLastError()); + goto Error; + } + } + } else { + + i = completedOv - pOvList; + + printf("Number of bytes written by request number %Iu is %d\n", + i, numberOfBytesTransferred); + + if ( WriteFile( hDevice, + buf + (i * BUFFER_SIZE), + BUFFER_SIZE, + NULL, + completedOv) == 0) { + error = GetLastError(); + if (error != ERROR_IO_PENDING) { + printf("%Iu th write failed %d \n", i, GetLastError()); + goto Error; + } + } + } + } + +Error: + if (hDevice != INVALID_HANDLE_VALUE) { + CloseHandle(hDevice); + } + + if (hCompletionPort) { + CloseHandle(hCompletionPort); + } + + if (pOvList) { + free(pOvList); + } + if (buf) { + free(buf); + } + + return 1; + +} + + +int +_cdecl +main( + _In_ int argc, + _In_reads_(argc) LPSTR *argv + ) +/*++ +Routine Description: + + Entry point to rwbulk.exe + Parses cmdline, performs user-requested tests + +Arguments: + + argc, argv standard console 'c' app arguments + +Return Value: + + Zero + +--*/ + +{ + char * pinBuf = NULL; + char * poutBuf = NULL; + ULONG nBytesRead; + ULONG nBytesWrite = 0; + int ok; + int retValue = 0; + UINT success; + HANDLE hRead = INVALID_HANDLE_VALUE; + HANDLE hWrite = INVALID_HANDLE_VALUE; + ULONG fail = 0L; + ULONG i; + + + Parse(argc, argv ); + + // + // dump USB configuation and pipe info + // + if (G_fDumpUsbConfig) { + DumpUsbConfig(); + } + + if (G_fPlayWithDevice) { + PlayWithDevice(); + goto exit; + } + + if (G_fPerformAsyncIo) { + HANDLE th1; + + // + // Create a reader thread + // + th1 = CreateThread( NULL, // Default Security Attrib. + 0, // Initial Stack Size, + AsyncIo, // Thread Func + (LPVOID)READER_TYPE, + 0, // Creation Flags + NULL ); // Don't need the Thread Id. + + if (th1 == NULL) { + printf("Couldn't create reader thread - error %d\n", GetLastError()); + retValue = 1; + goto exit; + } + + // + // Use this thread for peforming write. + // + AsyncIo((PVOID)WRITER_TYPE); + + goto exit; + } + + // + // doing a read, write, or both test + // + if ((G_fRead) || (G_fWrite)) { + + if (G_fRead) { + if ( G_fDumpReadData ) { // round size to sizeof ULONG for readable dumping + while( G_ReadLen % sizeof( ULONG ) ) { + G_ReadLen++; + } + } + + // + // open the output file + // + hRead = OpenDevice(TRUE); + if(hRead == INVALID_HANDLE_VALUE) { + retValue = 1; + goto exit; + } + + pinBuf = malloc(G_ReadLen); + } + + if (G_fWrite) { + if ( G_fDumpReadData ) { // round size to sizeof ULONG for readable dumping + while( G_WriteLen % sizeof( ULONG ) ) { + G_WriteLen++; + } + } + + // + // open the output file + // + hWrite = OpenDevice(TRUE); + if(hWrite == INVALID_HANDLE_VALUE) { + retValue = 1; + goto exit; + } + + poutBuf = malloc(G_WriteLen); + } + + for (i = 0; i < G_IterationCount; i++) { + ULONG j; + + if (G_fWrite && poutBuf && hWrite != INVALID_HANDLE_VALUE) { + + PULONG pOut = (PULONG) poutBuf; + ULONG numLongs = G_WriteLen / sizeof( ULONG ); + + // + // put some data in the output buffer + // + for (j=0; j<numLongs; j++) { + *(pOut+j) = j; + } + + // + // send the write + // + success = WriteFile(hWrite, poutBuf, G_WriteLen, &nBytesWrite, NULL); + if(success == 0) { + printf("WriteFile failed - error %d\n", GetLastError()); + retValue = 1; + goto exit; + } + printf("Write (%04.4u) : request %06.6u bytes -- %06.6u bytes written\n", + i, G_WriteLen, nBytesWrite); + + assert(nBytesWrite == G_WriteLen); + } + + if (G_fRead && pinBuf) { + + success = ReadFile(hRead, pinBuf, G_ReadLen, &nBytesRead, NULL); + if(success == 0) { + printf("ReadFile failed - error %d\n", GetLastError()); + retValue = 1; + goto exit; + } + + printf("Read (%04.4u) : request %06.6u bytes -- %06.6u bytes read\n", + i, G_ReadLen, nBytesRead); + + if (G_fWrite && poutBuf) { + + // + // validate the input buffer against what + // we sent to the 82930 (loopback test) + // + ok = Compare_Buffs(pinBuf, nBytesRead, poutBuf, nBytesWrite); + + if( G_fDumpReadData ) { + printf("Dumping read buffer\n"); + Dump( (PUCHAR) pinBuf, nBytesRead ); + printf("Dumping write buffer\n"); + Dump( (PUCHAR) poutBuf, nBytesRead ); + } + assert(ok); + + if(ok != 1) { + fail++; + } + + assert(G_ReadLen == G_WriteLen); + assert(nBytesRead == G_ReadLen); + } + } + } + + } + +exit: + + if (pinBuf) { + free(pinBuf); + } + + if (poutBuf) { + free(poutBuf); + } + + // close devices if needed + if (hRead != INVALID_HANDLE_VALUE) { + CloseHandle(hRead); + } + + if (hWrite != INVALID_HANDLE_VALUE) { + _Analysis_assume_(hWrite != NULL); + CloseHandle(hWrite); + } + + return retValue; +} + + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/testapp.rc b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/testapp.rc new file mode 100644 index 00000000..3947204a --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_testapp/testapp.rc @@ -0,0 +1,12 @@ +#include <windows.h> + +#include <ntverp.h> + +#define VER_FILETYPE VFT_DLL +#define VER_FILESUBTYPE VFT2_UNKNOWN +#define VER_FILEDESCRIPTION_STR "OSRUSBFX2 Bulk & Isoch Read and Write test App" +#define VER_INTERNALNAME_STR "osrusbfx2.exe" +#define VER_ORIGINALFILENAME_STR "osrusbfx2.exe" + +#include <common.ver> + diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/CppWindowsService.cpp b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/CppWindowsService.cpp new file mode 100644 index 00000000..98a3975c --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/CppWindowsService.cpp @@ -0,0 +1,74 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + CppWindowsService.cpp + +Abstract: + + The file defines the entry point of the application. According to the + arguments in the command line, the function installs or uninstalls or + starts the service by calling into different routines. + +Environment: + + User mode + +--*/ + +#pragma region Includes +#include <stdio.h> +#include <windows.h> +#include "ServiceBase.h" +#include "SampleService.h" +#pragma endregion + +// +// Settings of the service +// + +// +// Internal name of the service +// +#define SERVICE_NAME L"OsrUsbFx2UmUserSvc" + + +/*++ + +Routine Description: + + Entry point for the service. + +Arguments: + + Argc - The number of command line arguments + + Argv - The array of command line arguments + +Return Value: + + VOID + +--*/ +INT +wmain( + INT Argc, + WCHAR *Argv[] + ) +{ + CSampleService service(SERVICE_NAME); + + if (!CServiceBase::Run(service)) + { + wprintf(L"Service failed to run w/err 0x%08lx\n", GetLastError()); + } + + return 0; +}
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Main.cpp b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Main.cpp new file mode 100644 index 00000000..a02ac24a --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Main.cpp @@ -0,0 +1,1217 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + Main.cpp + +Abstract: + + Implements the functions to control the OSR USB FX2 device. + +Environment: + + User mode + +--*/ + +#include "Main.h" +#include "Utils.h" + +// +// Keep track of where the OSRFX2 device's bar graph currently is. +// +INT CurrentBar; +BAR_GRAPH_STATE BarGraphState; + +/*++ + +Routine Description: + + Sets the variables in this service to their default values. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +SetVariables() +{ + CurrentBar = 0; +} + + +/*++ + +Routine Description: + + Retrieves the device path of a given interface. + +Arguments: + + InterfaceGuid - The GUID of the interface to search for + + DevicePath - The resulting device path + + DevicePathLength - The length of DevicePath + +Return Value: + + TRUE if the function succeeded and FALSE otherwise. Errors + are logged in the Application event log. + +--*/ +_Success_(return) +BOOL +GetDevicePath( + _In_ LPGUID InterfaceGuid, + _Out_writes_z_(DevicePathLength) PWCHAR DevicePath, + _In_ size_t DevicePathLength + ) +{ + HRESULT hr = E_FAIL; + CONFIGRET cr = CR_SUCCESS; + PWSTR DeviceInterfaceList = NULL; + ULONG DeviceInterfaceListLength = 0; + PWSTR NextInterface; + + // + // Determine if there are any interfaces that match the OSRFX2 device. + // + cr = CM_Get_Device_Interface_List_Size(&DeviceInterfaceListLength, + InterfaceGuid, + NULL, + CM_GET_DEVICE_INTERFACE_LIST_PRESENT); + + if (cr != CR_SUCCESS) + { + WriteToErrorLog(L"CM_Get_DeviceInterface_List_Size", + CM_MapCrToWin32Err(cr, ERROR_FILE_NOT_FOUND)); + goto cleanup; + } + + if (DeviceInterfaceListLength < 1) + { + WriteToErrorLog(L"CM_Get_DeviceInterface_List_Size", + CM_MapCrToWin32Err(cr, ERROR_EMPTY)); + goto cleanup; + } + + DeviceInterfaceList = (PWSTR)malloc(DeviceInterfaceListLength * sizeof(WCHAR)); + + if (DeviceInterfaceList == NULL) + { + WriteToEventLog(L"Failed to allocate memory for the device interface list", + TRACE_LEVEL_ERROR); + goto cleanup; + } + + cr = CM_Get_Device_Interface_List(InterfaceGuid, + NULL, + DeviceInterfaceList, + DeviceInterfaceListLength, + CM_GET_DEVICE_INTERFACE_LIST_PRESENT); + + if (cr != CR_SUCCESS) + { + WriteToErrorLog(L"CM_Get_Device_Interface_List", + CM_MapCrToWin32Err(cr, ERROR_FILE_NOT_FOUND)); + goto cleanup; + } + + if (*DeviceInterfaceList == UNICODE_NULL) + { + WriteToEventLog(L"CM_Get_Device_Interface_List returned an empty list", + TRACE_LEVEL_ERROR); + } + + // + // This sample only expects one interface for the OSRFX2 device. For other + // devices, though, it maybe necessary to sift through the interfaces + // from CM_Get_Device_Interface_List in order to find the correct device. + // + NextInterface = DeviceInterfaceList + wcslen(DeviceInterfaceList) + 1; + + if (*NextInterface != UNICODE_NULL) + { + WriteToEventLog(L"More than one device interface instance found. " + "Selecting first matching device.", + TRACE_LEVEL_WARNING); + } + + hr = StringCchCopy(DevicePath, DevicePathLength, DeviceInterfaceList); + + if (FAILED(hr)) + { + WriteToErrorLog(L"StringCchCopy", HRESULT_CODE(hr)); + goto cleanup; + } + +cleanup: + + if (DeviceInterfaceList != NULL) + { + free(DeviceInterfaceList); + } + + return (cr == CR_SUCCESS); +} + + +/*++ + +Routine Description: + + Opens up the OSR USB FX2 device handle. + +Arguments: + + Synchronous - Whether or not this device should be opened for syncrhonous + access + +Return Value: + + The handle to the OSR USB FX2 device. + +--*/ +_Check_return_ +_Ret_notnull_ +_Success_(return != INVALID_HANDLE_VALUE) +HANDLE +OpenDevice( + _In_ BOOL Synchronous + ) +{ + HANDLE DeviceHandle = INVALID_HANDLE_VALUE; + WCHAR DeviceName[MAX_DEVPATH_LENGTH]; + + if (!GetDevicePath((LPGUID)&GUID_DEVINTERFACE_OSRUSBFX2, + DeviceName, + sizeof(DeviceName) / sizeof(DeviceName[0]))) + { + goto cleanup; + } + + // + // Open a handle to the interface. + // + if (Synchronous) + { + DeviceHandle = CreateFile(DeviceName, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_WRITE | FILE_SHARE_READ, + NULL, // default security + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + } + else + { + DeviceHandle = CreateFile(DeviceName, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_WRITE | FILE_SHARE_READ, + NULL, // default security + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, + NULL); + } + + if (DeviceHandle == INVALID_HANDLE_VALUE) + { + WriteToErrorLog(L"CreateFile", GetLastError()); + } + else + { + WriteToEventLog(L"Opened Device Successfully", TRACE_LEVEL_INFORMATION); + } + +cleanup: + + return DeviceHandle; +} + + +/*++ + +Routine Description: + + Handles an interface arrival notification. + +Arguments: + + Context - The callback context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +InterfaceArrivalAction( + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + + // + // Now that the interface has arrived, open a handle to it, and then + // register that handle for device events. + // + EnterCriticalSection(&Context->Lock); + + if (Context->DeviceInterfaceHandle != INVALID_HANDLE_VALUE) + { + // + // The handle was already retrieved. + // + Err = ERROR_SUCCESS; + goto cleanup; + } + + Context->DeviceInterfaceHandle = OpenDevice(FALSE); + + if (Context->DeviceInterfaceHandle == INVALID_HANDLE_VALUE) + { + Err = GetLastError(); + WriteToErrorLog(L"Could not open device interface", Err); + goto cleanup; + } + + Err = RegisterDeviceNotifications(Context); + + if (Err != ERROR_SUCCESS) + { + WriteToErrorLog(L"Could not register device notifications", Err); + goto cleanup; + } + +cleanup: + + LeaveCriticalSection(&Context->Lock); + + return Err; +} + + +/*++ + +Routine Description: + + Handles an interface arrival notification. + +Arguments: + + hNotify - The notification that fired the callback + + hContext - The callback context + + Action - The type of notification + + EventData - Additional information about the callback + + EventDataSize - The size of EventData + +Return Value: + + A Win32 error code. + +--*/ +DWORD +InterfaceCallback( + _In_ HCMNOTIFICATION hNotify, + _In_ PVOID hContext, + _In_ CM_NOTIFY_ACTION Action, + _In_ PCM_NOTIFY_EVENT_DATA EventData, + _In_ DWORD EventDataSize + ) +{ + DWORD Err = ERROR_SUCCESS; + PDEVICE_CONTEXT Context = (PDEVICE_CONTEXT)hContext; + + // + // Validate Context. + // + if (Context == NULL) + { + goto cleanup; + } + + if (Action == CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL) + { + Err = InterfaceArrivalAction(Context); + } + +cleanup: + + return Err; +} + + +/*++ + +Routine Description: + + Registers the service for notifications using the notification handle in + Context. + +Arguments: + + Context - The callback context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +RegisterInterfaceNotifications( + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + CONFIGRET cr; + CM_NOTIFY_FILTER NotifyFilter = {0}; + + if (Context == NULL) + { + goto cleanup; + } + + ZeroMemory(&NotifyFilter, sizeof(NotifyFilter)); + NotifyFilter.cbSize = sizeof(NotifyFilter); + NotifyFilter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE; + NotifyFilter.u.DeviceInterface.ClassGuid = GUID_DEVINTERFACE_OSRUSBFX2; + + cr = CM_Register_Notification(&NotifyFilter, + (PVOID)Context, + (PCM_NOTIFY_CALLBACK)InterfaceCallback, + &Context->InterfaceNotificationHandle); + + if (cr != CR_SUCCESS) + { + Err = CM_MapCrToWin32Err(cr, ERROR_INVALID_DATA); + WriteToErrorLog(L"CM_Register_Notification", Err); + goto cleanup; + } + +cleanup: + + return Err; +} + + +/*++ + +Routine Description: + + Unregister for interface notifications. Note, this routine deadlocks + when called from an interface callback. + +Arguments: + + Context - The callback context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +UnregisterInterfaceNotifications( + _In_ PDEVICE_CONTEXT Context + ) +{ + CONFIGRET cr; + + if (Context->InterfaceNotificationHandle != NULL) + { + cr = CM_Unregister_Notification(Context->InterfaceNotificationHandle); + + Context->InterfaceNotificationHandle = NULL; + } + + return CM_MapCrToWin32Err(cr, ERROR_INVALID_DATA); +} + + +/*++ + +Routine Description: + + Callback for when a device is being query removed. + +Arguments: + + Context - The callback context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +DeviceQueryRemoveAction( + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + + EnterCriticalSection(&Context->Lock); + + if (Context->DeviceInterfaceHandle != INVALID_HANDLE_VALUE) + { + // + // Close open handles to allow the device to exit + // + CloseHandle(Context->DeviceInterfaceHandle); + + Context->DeviceInterfaceHandle = INVALID_HANDLE_VALUE; + } + + LeaveCriticalSection(&Context->Lock); + + return Err; +} + + +/*++ + +Routine Description: + + This callback avoids a deadlock when unregistering device notifications. + Rather than calling CM_Unregister_Notification from the callback, the + callback gives that work to a separate thread to avoid deadlock. + +Arguments: + + Instance - The thread's callback instance + + hContext - The callback context + + pWork - The thread handle + +Return Value: + + VOID + +--*/ +VOID +CALLBACK +UnregisterWorkerThreadCallback( + _Inout_ PTP_CALLBACK_INSTANCE Instance, + _Inout_opt_ PVOID hContext, + _Inout_ PTP_WORK pWork + ) +{ + PDEVICE_CONTEXT Context = (PDEVICE_CONTEXT)hContext; + + EnterCriticalSection(&Context->Lock); + + UnregisterDeviceNotifications(Context); + + // + // Close the device handle. + // + if (Context->DeviceInterfaceHandle != INVALID_HANDLE_VALUE) + { + CloseHandle(Context->DeviceInterfaceHandle); + + Context->DeviceInterfaceHandle = INVALID_HANDLE_VALUE; + } + + LeaveCriticalSection(&Context->Lock); +} + + +/*++ + +Routine Description: + + Handles a device query remove failed notification. + +Arguments: + + hNotify - The notification that spurred this callback + + Context - The callback context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +DeviceQueryRemoveFailedAction( + _In_ HCMNOTIFICATION hNotify, + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + + EnterCriticalSection(&Context->Lock); + + // + // In case this callback fires before the registration call returns, make + // sure the notification handle is properly set. + // + Context->InterfaceNotificationHandle = hNotify; + + // + // Unregister the device callback, and then close the handle + // + if (!Context->Unregister) + { + Context->Unregister = TRUE; + SubmitThreadpoolWork(Context->Work); + } + + LeaveCriticalSection(&Context->Lock); + + // + // Wait for the callback and then re-register the device + // + WaitForThreadpoolWorkCallbacks(Context->Work, FALSE); + + EnterCriticalSection(&Context->Lock); + + if (Context->DeviceInterfaceHandle == INVALID_HANDLE_VALUE) + { + Context->DeviceInterfaceHandle = OpenDevice(FALSE); + } + + if (Context->DeviceInterfaceHandle != INVALID_HANDLE_VALUE) + { + RegisterDeviceNotifications(Context); + } + + LeaveCriticalSection(&Context->Lock); + + return Err; +} + + +/*++ + +Routine Description: + + Handles a device remove pending notification. + +Arguments: + + hNotify - The notification that spurred this callback + + Context - The callback context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +DeviceRemovePendingAction( + _In_ HCMNOTIFICATION hNotify, + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + + EnterCriticalSection(&Context->Lock); + + // + // In case this callback fires before the registration call returns, make + // sure the notification handle is properly set. + // + Context->InterfaceNotificationHandle = hNotify; + + // + // Unregister the device callback, and then close the handle + // + if (!Context->Unregister) + { + Context->Unregister = TRUE; + SubmitThreadpoolWork(Context->Work); + } + + LeaveCriticalSection(&Context->Lock); + + return Err; +} + + +/*++ + +Routine Description: + + Handles a device remove complete notification. + +Arguments: + + hNotify - The notification that spurred this callback + + Context - The callback context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +DeviceRemoveCompleteAction( + _In_ HCMNOTIFICATION hNotify, + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + + EnterCriticalSection(&Context->Lock); + + // + // In case this callback fires before the registration call returns, make + // sure the notification handle is properly set. + // + Context->InterfaceNotificationHandle = hNotify; + + // + // Unregister the device callback, and then close the handle + // + if (!Context->Unregister) + { + Context->Unregister = TRUE; + SubmitThreadpoolWork(Context->Work); + } + + LeaveCriticalSection(&Context->Lock); + + return Err; +} + + +/*++ + +Routine Description: + + Handles device notifications. + +Arguments: + + hNotify - The notification that spurred this callback + + hContext - The callback context + + Action - The type of callback + + EventData - Additional information about this callback + + EventDataSize - The size of EventData + +Return Value: + + A Win32 error code. + +--*/ +DWORD +DeviceCallback( + _In_ HCMNOTIFICATION hNotify, + _In_ PVOID hContext, + _In_ CM_NOTIFY_ACTION Action, + _In_ PCM_NOTIFY_EVENT_DATA EventData, + _In_ DWORD EventDataSize + ) +{ + DWORD Err = ERROR_SUCCESS; + PDEVICE_CONTEXT Context = (PDEVICE_CONTEXT)hContext; + + // + // Validate Context. + // + if (Context == NULL) + { + goto cleanup; + } + + switch (Action) + { + case CM_NOTIFY_ACTION_DEVICEQUERYREMOVE: + DeviceQueryRemoveAction(Context); + break; + + case CM_NOTIFY_ACTION_DEVICEQUERYREMOVEFAILED: + DeviceQueryRemoveFailedAction(hNotify, Context); + break; + + case CM_NOTIFY_ACTION_DEVICEREMOVEPENDING: + DeviceRemovePendingAction(hNotify, Context); + break; + + case CM_NOTIFY_ACTION_DEVICEREMOVECOMPLETE: + DeviceRemoveCompleteAction(hNotify, Context); + break; + } + +cleanup: + + return Err; +} + + +/*++ + +Routine Description: + + Register for device notifications. + +Arguments: + + Context - The callback context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +RegisterDeviceNotifications( + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + CONFIGRET cr; + CM_NOTIFY_FILTER NotifyFilter = {0}; + + NotifyFilter.cbSize = sizeof(NotifyFilter); + NotifyFilter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEHANDLE; + NotifyFilter.u.DeviceHandle.hTarget = Context->DeviceInterfaceHandle; + + cr = CM_Register_Notification(&NotifyFilter, + (PVOID)Context, + (PCM_NOTIFY_CALLBACK)DeviceCallback, + &Context->DeviceNotificationHandle); + + if (cr != CR_SUCCESS) + { + Err = CM_MapCrToWin32Err(cr, ERROR_INVALID_DATA); + WriteToEventLog(L"Could not register for notifications", TRACE_LEVEL_WARNING); + goto cleanup; + } + + Context->Unregister = FALSE; + +cleanup: + + return Err; +} + + +/*++ + +Routine Description: + + Unregister for device notifications. + +Arguments: + + Context - The callback context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +UnregisterDeviceNotifications( + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + CONFIGRET cr; + + if (Context->DeviceNotificationHandle != NULL) + { + cr = CM_Unregister_Notification(Context->DeviceNotificationHandle); + + if (cr != CR_SUCCESS) + { + Err = CM_MapCrToWin32Err(cr, ERROR_INVALID_DATA); + WriteToEventLog(L"Could not unregister notifications", TRACE_LEVEL_WARNING); + } + + Context->DeviceNotificationHandle = NULL; + } + + return Err; +} + + +/*++ + +Routine Description: + + Initialize the given PDEVICE_CONTEXT. + +Arguments: + + Context - The callback context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +InitializeContext( + _Out_ PDEVICE_CONTEXT *Context + ) +{ + DWORD Err = ERROR_SUCCESS; + BOOL LockInitialized = FALSE; + BOOL LockEntered = FALSE; + BOOL InterfaceNotificationsInitialized = FALSE; + BOOL DeviceNotificationsInitialized = FALSE; + PDEVICE_CONTEXT DeviceContext; + + DeviceContext = (PDEVICE_CONTEXT)malloc(sizeof(DEVICE_CONTEXT)); + + if (DeviceContext == NULL) + { + Err = ERROR_OUTOFMEMORY; + goto cleanup; + } + + DeviceContext->DeviceInterfaceHandle = INVALID_HANDLE_VALUE; + DeviceContext->LockEnabled = FALSE; + DeviceContext->InterfaceNotificationsEnabled = FALSE; + DeviceContext->DeviceNotificationsEnabled = FALSE; + + InitializeCriticalSection(&DeviceContext->Lock); + DeviceContext->LockEnabled = TRUE; + + DeviceContext->Work = CreateThreadpoolWork(UnregisterWorkerThreadCallback, (PVOID)DeviceContext, NULL); + + if (DeviceContext->Work == NULL) + { + Err = GetLastError(); + WriteToErrorLog(L"Could not create worker thread callback", Err); + goto cleanup; + } + + DeviceContext->DeviceNotificationHandle = NULL; + DeviceContext->InterfaceNotificationHandle = NULL; + + // + // Register for device interface events to open and close the handle to + // the interface. + // + Err = RegisterInterfaceNotifications(DeviceContext); + + if (Err != ERROR_SUCCESS) + { + WriteToErrorLog(L"Could not register notifications", Err); + goto cleanup; + } + + DeviceContext->InterfaceNotificationsEnabled = TRUE; + + EnterCriticalSection(&DeviceContext->Lock); + LockEntered = TRUE; + + // + // The interface may already have arrived while registering for + // notifications. The lock could be moved earlier, but for sample + // purposes this is the proper way to initialize notifications. + // + if (DeviceContext->DeviceInterfaceHandle == INVALID_HANDLE_VALUE) + { + DeviceContext->DeviceInterfaceHandle = OpenDevice(FALSE); + } + + if (DeviceContext->DeviceInterfaceHandle != INVALID_HANDLE_VALUE) + { + Err = RegisterDeviceNotifications(DeviceContext); + + if (Err != ERROR_SUCCESS) + { + WriteToErrorLog(L"Could not register device notifications", Err); + goto cleanup; + } + + DeviceContext->DeviceNotificationsEnabled = TRUE; + } + + // + // If OpenDevice ends up returning INVALID_HANDLE_VALUE, that's fine + // since a notification for the interface will arrive later. + // + +cleanup: + + if (LockEntered) + { + LeaveCriticalSection(&DeviceContext->Lock); + } + + *Context = DeviceContext; + DeviceContext = NULL; + + if (DeviceContext != NULL) + { + CloseContext(DeviceContext); + } + + return Err; +} + + +/*++ + +Routine Description: + + Clean up the given PDEVICE_CONTEXT. + +Arguments: + + Context - The callback context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +CloseContext( + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + BOOL Unregister = FALSE; + + if (Context == NULL) + { + // + // Nothing to remove. + // + goto cleanup; + } + + EnterCriticalSection(&Context->Lock); + + if (!Context->Unregister) + { + // + // Unregister from the callback here. + // + Unregister = TRUE; + Context->Unregister = TRUE; + } + + LeaveCriticalSection(&Context->Lock); + + // + // Unregister from the interface first, so that re-appearance of the interface + // doesn't cause us to register device events again. + // + if (Context->InterfaceNotificationsEnabled) + { + Err = UnregisterInterfaceNotifications(Context); + + if (Err != ERROR_SUCCESS) + { + WriteToErrorLog(L"Could not unregister interface notifications", Err); + } + } + + if (Unregister) + { + if (Context->DeviceNotificationsEnabled) + { + Err = UnregisterDeviceNotifications(Context); + + if (Err != ERROR_SUCCESS) + { + WriteToErrorLog(L"Could not unregister device notifications", Err); + } + } + } + else + { + WaitForThreadpoolWorkCallbacks(Context->Work, FALSE); + } + + // + // No need to lock here, UnregisterDeviceNotifications will wait for all + // outstanding callbacks before returning. + // + if (Context->DeviceInterfaceHandle != INVALID_HANDLE_VALUE) + { + CloseHandle(Context->DeviceInterfaceHandle); + + Context->DeviceInterfaceHandle = INVALID_HANDLE_VALUE; + } + + if (Context->Work != NULL) + { + CloseThreadpoolWork(Context->Work); + } + + DeleteCriticalSection(&Context->Lock); + + free(Context); + +cleanup: + + return Err; +} + +/*++ + +Routine Description: + + Turns off all of the bar graph lights on the OSR USB FX2 device. + +Arguments: + + Context - The callback context + +Return Value: + + VOID + +--*/ +DWORD +ClearAllBars( + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + ULONG BytesReturned; + + BarGraphState.BarsAsUChar = 0; + + if (!DeviceIoControl(Context->DeviceInterfaceHandle, + IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, + &BarGraphState, // Pointer to InBuffer + sizeof(BAR_GRAPH_STATE), // Length of InBuffer + NULL, // Pointer to OutBuffer + 0, // Length of OutBuffer + &BytesReturned, // BytesReturned + 0)) // Pointer to Overlapped structure + { + Err = GetLastError(); + WriteToErrorLog(L"DeviceIOControl", Err); + goto cleanup; + } + +cleanup: + + return Err; +} + + +/*++ + +Routine Description: + + Lights the next bar on the OSR USB FX2 device. + +Arguments: + + Context - The callback context + +Return Value: + + VOID + +--*/ +DWORD +LightNextBar( + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + ULONG BytesReturned; + + // + // Normalize to 0-7 + // + CurrentBar += 1; + + if (CurrentBar > 7) + { + CurrentBar = 0; + } + + BarGraphState.BarsAsUChar = 1 << (UCHAR)CurrentBar; + + if (!DeviceIoControl(Context->DeviceInterfaceHandle, + IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY, + &BarGraphState, // Pointer to InBuffer + sizeof(BAR_GRAPH_STATE), // Length of InBuffer + NULL, // Pointer to OutBuffer + 0, // Length of OutBuffer + &BytesReturned, // BytesReturned + 0)) // Pointer to Overlapped structure + { + Err = GetLastError(); + WriteToErrorLog(L"DeviceIOControl", Err); + goto cleanup; + } + +cleanup: + + return Err; +} + +/*++ + +Routine Description: + + Lights the next bar on the OSRFX2 device. + +Arguments: + + Context - The device context + +Return Value: + + A Win32 error code. + +--*/ +DWORD +ControlDevice( + _In_ PDEVICE_CONTEXT Context + ) +{ + DWORD Err = ERROR_SUCCESS; + + EnterCriticalSection(&Context->Lock); + + Err = ClearAllBars(Context); + + if (Err != ERROR_SUCCESS) + { + goto cleanup; + } + + Err = LightNextBar(Context); + + if (Err != ERROR_SUCCESS) + { + goto cleanup; + } + +cleanup: + + LeaveCriticalSection(&Context->Lock); + + return Err; +}
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Main.h b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Main.h new file mode 100644 index 00000000..3b8be711 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Main.h @@ -0,0 +1,328 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + Main.h + +Abstract: + + Implements the functions to control the OSR USB FX2 device. + +Environment: + + User mode + +--*/ + +#pragma once + +#include <Windows.h> +#include <devioctl.h> +#include <cfgmgr32.h> +#include <stdio.h> +#include <stdlib.h> +#include <assert.h> +#include <strsafe.h> +#include <driverspecs.h> +#include <basetyps.h> + +#include <initguid.h> + +// {573E8C73-0CB4-4471-A1BF-FAB26C31D384} +DEFINE_GUID(GUID_DEVINTERFACE_OSRUSBFX2, + 0x573e8c73, 0xcb4, 0x4471, 0xa1, 0xbf, 0xfa, 0xb2, 0x6c, 0x31, 0xd3, 0x84); + +// +// Most device interface paths will fit into a buffer of this size. +// However, some could be longer, and a larger buffer or dynamically +// allocated buffer may be needed for robust code. +// +#define MAX_DEVPATH_LENGTH 1024 + +#pragma warning(push) +#pragma warning(disable:4201) // nameless struct/union +#pragma warning(disable:4214) // bit field types other than int + +typedef struct _DEVICE_CONTEXT { + HANDLE DeviceInterfaceHandle; + CRITICAL_SECTION Lock; + BOOL LockEnabled; + PTP_WORK Work; + BOOL Unregister; + HCMNOTIFICATION InterfaceNotificationHandle; + BOOL InterfaceNotificationsEnabled; + HCMNOTIFICATION DeviceNotificationHandle; + BOOL DeviceNotificationsEnabled; +} DEVICE_CONTEXT, *PDEVICE_CONTEXT; + +// +// Define the structures that will be used by the IOCTL +// interface to the driver +// + +// +// BAR_GRAPH_STATE +// +// BAR_GRAPH_STATE is a bit field structure with each +// bit corresponding to one of the bar graph on the +// OSRFX2 Development Board +// +#include <pshpack1.h> +typedef struct _BAR_GRAPH_STATE { + + union { + + struct { + // + // Individual bars starting from the + // top of the stack of bars + // + // NOTE: There are actually 10 bars, + // but the very top two do not light + // and are not counted here + // + UCHAR Bar1 : 1; + UCHAR Bar2 : 1; + UCHAR Bar3 : 1; + UCHAR Bar4 : 1; + UCHAR Bar5 : 1; + UCHAR Bar6 : 1; + UCHAR Bar7 : 1; + UCHAR Bar8 : 1; + }; + + // + // The state of all the bar graph as a single + // UCHAR + // + UCHAR BarsAsUChar; + + }; + +}BAR_GRAPH_STATE, *PBAR_GRAPH_STATE; + +// +// SWITCH_STATE +// +// SWITCH_STATE is a bit field structure with each +// bit corresponding to one of the switches on the +// OSRFX2 Development Board +// +typedef struct _SWITCH_STATE { + + union { + struct { + // + // Individual switches starting from the + // left of the set of switches + // + UCHAR Switch1 : 1; + UCHAR Switch2 : 1; + UCHAR Switch3 : 1; + UCHAR Switch4 : 1; + UCHAR Switch5 : 1; + UCHAR Switch6 : 1; + UCHAR Switch7 : 1; + UCHAR Switch8 : 1; + }; + + // + // The state of all the switches as a single + // UCHAR + // + UCHAR SwitchesAsUChar; + + }; + + +}SWITCH_STATE, *PSWITCH_STATE; + +#include <poppack.h> + +#pragma warning(pop) + +#define IOCTL_INDEX 0x800 +#define FILE_DEVICE_OSRUSBFX2 65500U + +#define IOCTL_OSRUSBFX2_GET_CONFIG_DESCRIPTOR CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX, \ + METHOD_BUFFERED, \ + FILE_READ_ACCESS) + +#define IOCTL_OSRUSBFX2_RESET_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 1, \ + METHOD_BUFFERED, \ + FILE_WRITE_ACCESS) + +#define IOCTL_OSRUSBFX2_REENUMERATE_DEVICE CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 3, \ + METHOD_BUFFERED, \ + FILE_WRITE_ACCESS) + +#define IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 4, \ + METHOD_BUFFERED, \ + FILE_READ_ACCESS) + + +#define IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 5, \ + METHOD_BUFFERED, \ + FILE_WRITE_ACCESS) + + +#define IOCTL_OSRUSBFX2_READ_SWITCHES CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 6, \ + METHOD_BUFFERED, \ + FILE_READ_ACCESS) + + +#define IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 7, \ + METHOD_BUFFERED, \ + FILE_READ_ACCESS) + + +#define IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY CTL_CODE(FILE_DEVICE_OSRUSBFX2, \ + IOCTL_INDEX + 8, \ + METHOD_BUFFERED, \ + FILE_WRITE_ACCESS) + +#define IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE CTL_CODE(FILE_DEVICE_OSRUSBFX2,\ + IOCTL_INDEX + 9, \ + METHOD_OUT_DIRECT, \ + FILE_READ_ACCESS) + +/*++ + +Routine Description: + +Lights the next bar on the OSRFX2 device. + +Arguments: + +Context - The device context + +Return Value: + +A Win32 error code. + +--*/ +DWORD +ControlDevice(PDEVICE_CONTEXT Context); + + +/*++ + +Routine Description: + + Sets the variables in this service to their default values. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID SetVariables(VOID); + + +/*++ + +Routine Description: + + Opens up the OSR USB FX2 device handle. + +Arguments: + + Synchronous - Whether or not this device should be + opened for synchronous access + +Return Value: + + The handle to the OSR USB FX2 device. + +--*/ +HANDLE OpenDevice(_In_ BOOL Synchronous); + + +/*++ + +Routine Description: + +Register for device notifications. + +Arguments: + +Context - The callback context + +Return Value: + +A Win32 error code. + +--*/ +DWORD RegisterDeviceNotifications(PDEVICE_CONTEXT Context); + + +/*++ + +Routine Description: + +Unregister for device notifications. + +Arguments: + +Context - The callback context + +Return Value: + +A Win32 error code. + +--*/ +DWORD UnregisterDeviceNotifications(PDEVICE_CONTEXT Context); + + +/*++ + +Routine Description: + +Initialize the given PDEVICE_CONTEXT. + +Arguments: + +Context - The callback context + +Return Value: + +A Win32 error code. + +--*/ +DWORD InitializeContext(PDEVICE_CONTEXT* Context); + + +/*++ + +Routine Description: + +Clean up the given PDEVICE_CONTEXT. + +Arguments: + +Context - The callback context + +Return Value: + +A Win32 error code. + +--*/ +DWORD CloseContext(PDEVICE_CONTEXT Context);
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/SampleService.cpp b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/SampleService.cpp new file mode 100644 index 00000000..fd3d497f --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/SampleService.cpp @@ -0,0 +1,254 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + SampleService.cpp + +Abstract: + + Provides a sample service class that derives from the service base class - + CServiceBase. The sample service logs the service start and stop + information to the Application event log, and shows how to run the main + function of the service in a thread pool worker thread. + +Environment: + + User mode + +--*/ + +#pragma region Includes +#include "SampleService.h" +#include "ThreadPool.h" +#pragma endregion + +/*++ + +Routine Description: + + The constructor of CSampleService. It initializes a new instance + of the CSampleService class. The optional parameters (CanStop, + CanShutdown and CanPauseContinue) allow you to specify whether the + service can be stopped, paused and continued, or be notified when system + shutdown occurs. Inherits properties from the class CServiceBase. + +Arguments: + + ServiceName - The name of the service + + CanStop - The service can be stopped + + CanShutdown - The service is notified when system shutdown occurs + + CanPauseContinue - The service can be paused and continued + +Return Value: + + VOID + +--*/ +CSampleService::CSampleService( + PWSTR ServiceName, + BOOL CanStop, + BOOL CanShutdown, + BOOL CanPauseContinue + ) +: CServiceBase(ServiceName, CanStop, CanShutdown, CanPauseContinue) +{ + m_fStopping = FALSE; + + // + // Create a manual-reset event that is not signaled at first to indicate + // the stopped signal of the service. + // + m_hStoppedEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + + if (m_hStoppedEvent == NULL) + { + throw GetLastError(); + } +} + + +/*++ + +Routine Description: + + The virtual destructor of CSampleService. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +CSampleService::~CSampleService() +{ + if (m_hStoppedEvent) + { + CloseHandle(m_hStoppedEvent); + m_hStoppedEvent = NULL; + } +} + + +/*++ + +Routine Description: + + This function is executed when a Start command is sent to the + service by the SCM or when the operating system starts (for a service + that starts automatically). It specifies actions to take when the + service starts. In this code sample, OnStart logs a service-start + message to the Application log, and queues the main service function for + execution in a thread pool worker thread. + + NOTE: A service application is designed to be long running. Therefore, + it usually polls or monitors something in the system. The monitoring is + set up in the OnStart method. However, OnStart does not actually do the + monitoring. The OnStart method must return to the operating system after + the service's operation has begun. It must not loop forever or block. To + set up a simple monitoring mechanism, one general solution is to create + a timer in OnStart. The timer would then raise events in your code + periodically, at which time your service could do its monitoring. The + other solution is to spawn a new thread to perform the main service + functions, which is demonstrated in this code sample. + +Arguments: + + Argc - The number of command line arguments + + Argv - The array of command line arguments + +Return Value: + + VOID + +--*/ +VOID +CSampleService::OnStart( + DWORD Argc, + PWSTR *Argv + ) +{ + __debugbreak(); + + // + // Log a service start message to the Application log. + // + WriteToEventLog(L"SampleService in OnStart", + EVENTLOG_INFORMATION_TYPE); + + // + // Set up any variables the service needs. + // + SetVariables(); + + // + // Set up the context, and register for notifications. + // + InitializeContext(&m_Context); + + // + // Queue the main service function for execution in a worker thread. + // + CThreadPool::QueueUserWorkItem(&CSampleService::ServiceWorkerThread, this); +} + + +/*++ + +Routine Description: + + This method performs the main function of the service. It runs + on a thread pool worker thread. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +CSampleService::ServiceWorkerThread() +{ + // + // Periodically check if the service is stopping. + // + while (!m_fStopping) + { + // + // Perform main service function here... + // + + ControlDevice(m_Context); + + ::Sleep(2000); // Simulate some lengthy operations. + } + + // + // Signal the stopped event. + // + SetEvent(m_hStoppedEvent); +} + + +/*++ + +Routine Description: + + This function is executed when a Stop command is sent to the service by SCM. + It specifies actions to take when a service stops running. In this code + sample, OnStop logs a service-stop message to the Application log, and + waits for the finish of the main service function. + + Be sure to periodically call ReportServiceStatus() with + SERVICE_STOP_PENDING if the procedure is going to take a long time. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +CSampleService::OnStop() +{ + // + // Log a service stop message to the Application log. + // + WriteToEventLog(L"SampleService in OnStop", + EVENTLOG_INFORMATION_TYPE); + + // + // Indicate that the service is stopping and wait for the finish of the + // main service function (ServiceWorkerThread). + // + m_fStopping = TRUE; + + if (WaitForSingleObject(m_hStoppedEvent, INFINITE) != WAIT_OBJECT_0) + { + throw GetLastError(); + } + + // + // Clean up the context after the worker thread has finished. + // + CloseContext(m_Context); +}
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/SampleService.h b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/SampleService.h new file mode 100644 index 00000000..73be42e9 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/SampleService.h @@ -0,0 +1,187 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + SampleService.h + +Abstract: + + Provides a sample service class that derives from the service base class - + CServiceBase. The sample service logs the service start and stop + information to the Application event log, and shows how to run the main + function of the service in a thread pool worker thread. + +Environment: + + User mode + +--*/ + +#pragma once + +#include "ServiceBase.h" +#include "Main.h" + +class CSampleService : public CServiceBase +{ +public: + + /*++ + + Routine Description: + + The constructor of CSampleService. It initializes a new instance + of the CSampleService class. The optional parameters (CanStop, + CanShutdown and CanPauseContinue) allow you to specify whether the + service can be stopped, paused and continued, or be notified when system + shutdown occurs. Inherits properties from the class CServiceBase. + + Arguments: + + ServiceName - The name of the service + + CanStop - The service can be stopped + + CanShutdown - The service is notified when system shutdown occurs + + CanPauseContinue - The service can be paused and continued + + Return Value: + + VOID + + --*/ + CSampleService(PWSTR ServiceName, + BOOL CanStop = TRUE, + BOOL CanShutdown = TRUE, + BOOL CanPauseContinue = FALSE); + + /*++ + + Routine Description: + + The virtual destructor of CSampleService. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + virtual ~CSampleService(); + +protected: + + /*++ + + Routine Description: + + This function is executed when a Start command is sent to the + service by the SCM or when the operating system starts (for a service + that starts automatically). It specifies actions to take when the + service starts. In this code sample, OnStart logs a service-start + message to the Application log, and queues the main service function for + execution in a thread pool worker thread. + + NOTE: A service application is designed to be long running. Therefore, + it usually polls or monitors something in the system. The monitoring is + set up in the OnStart method. However, OnStart does not actually do the + monitoring. The OnStart method must return to the operating system after + the service's operation has begun. It must not loop forever or block. To + set up a simple monitoring mechanism, one general solution is to create + a timer in OnStart. The timer would then raise events in your code + periodically, at which time your service could do its monitoring. The + other solution is to spawn a new thread to perform the main service + functions, which is demonstrated in this code sample. + + Arguments: + + Argc - The number of command line arguments + + Argv - The array of command line arguments + + Return Value: + + VOID + + --*/ + virtual VOID OnStart(DWORD Argc, PWSTR *Argv); + + + /*++ + + Routine Description: + + This function is executed when a Stop command is sent to the service by SCM. + It specifies actions to take when a service stops running. In this code + sample, OnStop logs a service-stop message to the Application log, and + waits for the finish of the main service function. + + Be sure to periodically call ReportServiceStatus() with + SERVICE_STOP_PENDING if the procedure is going to take a long time. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + virtual VOID OnStop(); + + + /*++ + + Routine Description: + + This method performs the main function of the service. It runs + on a thread pool worker thread. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + VOID ServiceWorkerThread(); + +private: + + // + // Determines if the service is currently stopping. + // + BOOL m_fStopping; + + // + // The handle to wait for a stop event. + // + HANDLE m_hStoppedEvent; + + // + // The device context to manage notifications with. + // + // NOTE: + // Variables used for device notifications should normally be local. However, + // we must use a global variable here since there is a potential race condition + // when the service needs to restart during device installation that could + // cause the service to prevent the device from being restarted. So, this + // variable is global so that the service's OnStart and OnStart method can + // handle its creation and destruction. + // + PDEVICE_CONTEXT m_Context; +};
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/ServiceBase.cpp b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/ServiceBase.cpp new file mode 100644 index 00000000..4c20af2e --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/ServiceBase.cpp @@ -0,0 +1,794 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + ServiceBase.cpp + +Abstract: + + Provides a base class for a service that will exist as part of a service + application. CServiceBase must be derived from when creating a new service + class. + +Environment: + + User mode + +--*/ + +#pragma region Includes +#include "ServiceBase.h" +#include "Main.h" +#include "Utils.h" +#include <assert.h> +#include <strsafe.h> +#pragma endregion + + +#pragma region Static Members + +// +// Initialize the singleton service instance. +// +CServiceBase *CServiceBase::s_service = NULL; + + +/*++ + +Routine Description: + + Register the executable for a service with the Service Control + Manager (SCM). After you call Run(ServiceBase), the SCM issues a Start + command, which results in a call to the OnStart method in the service. + This method blocks until the service has stopped. + +Arguments: + + Service - The reference to a CServiceBase object. It will become the + singleton service instance of this service application. + +Return Value: + + If the function succeeds, the return value is TRUE. If the function + fails, the return value is FALSE. To get extended error information, + call GetLastError. + +--*/ +BOOL +CServiceBase::Run( + CServiceBase &Service + ) +{ + s_service = &Service; + + SERVICE_TABLE_ENTRY serviceTable[] = + { + { Service.m_name, ServiceMain }, + { NULL, NULL } + }; + + // + // Connects the main thread of a service process to the service control + // manager, which causes the thread to be the service control dispatcher + // thread for the calling process. This call returns when the service has + // stopped. The process should simply terminate when the call returns. + // + return StartServiceCtrlDispatcher(serviceTable); +} + + +/*++ + +Routine Description: + + The entry point for the service. It registers the handler function + for the service and starts the service. + +Arguments: + + Argc - The number of command line arguments + + Argv - The array of command line arguments + +Return Value: + + VOID + +--*/ +VOID +WINAPI +CServiceBase::ServiceMain( + DWORD Argc, + PWSTR *Argv + ) +{ + assert(s_service != NULL); + + // + // Register the handler function for the service. + // + s_service->m_statusHandle = RegisterServiceCtrlHandler(s_service->m_name, + ServiceCtrlHandler); + + if (s_service->m_statusHandle == NULL) + { + throw GetLastError(); + } + + // + // Start the service. + // + s_service->Start(Argc, Argv); +} + + +/*++ + +Routine Description: + + Called by the SCM whenever a control code is sent to the service. + +Arguments: + + CtrlCode - The control code. This parameter can be one of + the following values: + + SERVICE_CONTROL_CONTINUE + SERVICE_CONTROL_INTERROGATE + SERVICE_CONTROL_NETBINDADD + SERVICE_CONTROL_NETBINDDISABLE + SERVICE_CONTROL_NETBINDREMOVE + SERVICE_CONTROL_PARAMCHANGE + SERVICE_CONTROL_PAUSE + SERVICE_CONTROL_SHUTDOWN + SERVICE_CONTROL_STOP + + This parameter can also be a user-defined control + code ranging from 128 to 255. + +Return Value: + + VOID + +--*/ +VOID +WINAPI +CServiceBase::ServiceCtrlHandler( + DWORD Ctrl + ) +{ + switch (Ctrl) + { + case SERVICE_CONTROL_STOP: + s_service->Stop(); + break; + case SERVICE_CONTROL_PAUSE: + s_service->Pause(); + break; + case SERVICE_CONTROL_CONTINUE: + s_service->Continue(); + break; + case SERVICE_CONTROL_SHUTDOWN: + s_service->Shutdown(); + break; + case SERVICE_CONTROL_INTERROGATE: + break; + default: + break; + } +} + +#pragma endregion + + +#pragma region Service Constructor and Destructor + +/*++ + +Routine Description: + + The constructor of CServiceBase. It initializes a new instance + of the CServiceBase class. The optional parameters (CanStop, + CanShutdown and CanPauseContinue) allow you to specify whether the + service can be stopped, paused and continued, or be notified when system + shutdown occurs. + +Arguments: + + ServiceName - The name of the service + + CanStop - The service can be stopped + + CanShutdown - The service is notified when system shutdown occurs + + CanPauseContinue - The service can be paused and continued + +Return Value: + + VOID + +--*/ +CServiceBase::CServiceBase( + PWSTR ServiceName, + BOOL CanStop, + BOOL CanShutdown, + BOOL CanPauseContinue + ) +{ + // + // Service name must be a valid string and cannot be NULL. + // + m_name = (ServiceName == NULL) ? L"" : ServiceName; + + m_statusHandle = NULL; + + // + // The service runs in its own process. + // + m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + + // + // The service is starting. + // + m_status.dwCurrentState = SERVICE_START_PENDING; + + // + // The accepted commands of the service. + // + DWORD dwControlsAccepted = 0; + + if (CanStop) + { + dwControlsAccepted |= SERVICE_ACCEPT_STOP; + } + + if (CanShutdown) + { + dwControlsAccepted |= SERVICE_ACCEPT_SHUTDOWN; + } + + if (CanPauseContinue) + { + dwControlsAccepted |= SERVICE_ACCEPT_PAUSE_CONTINUE; + } + + m_status.dwControlsAccepted = dwControlsAccepted; + + m_status.dwWin32ExitCode = NO_ERROR; + m_status.dwServiceSpecificExitCode = 0; + m_status.dwCheckPoint = 0; + m_status.dwWaitHint = 0; + + SetupEvents(); +} + + +/*++ + +Routine Description: + + The virtual destructor of CServiceBase. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +CServiceBase::~CServiceBase() +{ + DestroyEvents(); +} + +#pragma endregion + + +#pragma region Service Start, Stop, Pause, Continue, and Shutdown + +/*++ + +Routine Description: + + This function starts the service. It calls the OnStart virtual function + in which you can specify the actions to take when the service starts. If + an error occurs during the startup, the error will be logged in the + Application event log, and the service will be stopped. + +Arguments: + + Argc - The number of command line arguments + + Argv - The array of command line arguments + +Return Value: + + VOID + +--*/ +VOID +CServiceBase::Start( + DWORD Argc, + PWSTR *Argv +) +{ + try + { + // + // Tell SCM that the service is starting. + // + SetServiceStatus(SERVICE_START_PENDING); + + // + // Perform service-specific initialization. + // + OnStart(Argc, Argv); + + // + // Tell SCM that the service is started. + // + SetServiceStatus(SERVICE_RUNNING); + } + catch (DWORD Error) + { + // + // Log the error. + // + WriteToErrorLog(L"Service Start", Error); + + // + // Set the service status to be stopped. + // + SetServiceStatus(SERVICE_STOPPED, Error); + } + catch (...) + { + // + // Log the error. + // + WriteToEventLog(L"Service failed to start.", EVENTLOG_ERROR_TYPE); + + // + // Set the service status to be stopped. + // + SetServiceStatus(SERVICE_STOPPED); + } +} + + +/*++ + +Routine Description: + + When implemented in a derived class, executes when a Start + command is sent to the service by the SCM or when the operating system + starts (for a service that starts automatically). Specifies actions to + take when the service starts. Be sure to periodically call + CServiceBase::SetServiceStatus() with SERVICE_START_PENDING if the + procedure is going to take long time. You may also consider spawning a + new thread in OnStart to perform time-consuming initialization tasks. + +Arguments: + + Argc - The number of command line arguments + + Argv - The array of command line arguments + +Return Value: + + VOID + +--*/ +VOID +CServiceBase::OnStart( + DWORD Argc, + PWSTR *Argv +) +{ + SetVariables(); +} + + +/*++ + +Routine Description: + + This function stops the service. It calls the OnStop virtual + function in which you can specify the actions to take when the service + stops. If an error occurs, the error will be logged in the Application + event log, and the service will be restored to the original state. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +CServiceBase::Stop() +{ + DWORD OriginalState = m_status.dwCurrentState; + + try + { + // + // Tell SCM that the service is stopping. + // + SetServiceStatus(SERVICE_STOP_PENDING); + + // + // Perform service-specific stop operations. + // + OnStop(); + + // + // Tell SCM that the service is stopped. + // + SetServiceStatus(SERVICE_STOPPED); + } + catch (DWORD Error) + { + // + // Log the error. + // + WriteToErrorLog(L"Service Stop", Error); + + // + // Set the orginal service status. + // + SetServiceStatus(OriginalState); + } + catch (...) + { + // + // Log the error. + // + WriteToEventLog(L"Service failed to stop.", EVENTLOG_ERROR_TYPE); + + // + // Set the orginal service status. + // + SetServiceStatus(OriginalState); + } +} + + +/*++ + +Routine Description: + + When implemented in a derived class, executes when a Stop + command is sent to the service by the SCM. Specifies actions to take + when a service stops running. Be sure to periodically call + CServiceBase::SetServiceStatus() with SERVICE_STOP_PENDING if the + procedure is going to take long time. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +CServiceBase::OnStop() +{ +} + + +/*++ + +Routine Description: + + The function pauses the service if the service supports pause + and continue. It calls the OnPause virtual function in which you can + specify the actions to take when the service pauses. If an error occurs, + the error will be logged in the Application event log, and the service + will become running. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +CServiceBase::Pause() +{ + try + { + // + // Tell SCM that the service is pausing. + // + SetServiceStatus(SERVICE_PAUSE_PENDING); + + // + // Perform service-specific pause operations. + // + OnPause(); + + // + // Tell SCM that the service is paused. + // + SetServiceStatus(SERVICE_PAUSED); + } + catch (DWORD Error) + { + // + // Log the error. + // + WriteToErrorLog(L"Service Pause", Error); + + // + // Tell SCM that the service is still running. + // + SetServiceStatus(SERVICE_RUNNING); + } + catch (...) + { + // + // Log the error. + // + WriteToEventLog(L"Service failed to pause.", EVENTLOG_ERROR_TYPE); + + // + // Tell SCM that the service is still running. + // + SetServiceStatus(SERVICE_RUNNING); + } +} + + +/*++ + +Routine Description: + + When implemented in a derived class, executes when a Pause + command is sent to the service by the SCM. Specifies actions to take + when a service pauses. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +CServiceBase::OnPause() +{ +} + + +/*++ + +Routine Description: + + The function resumes normal functioning after being paused if + the service supports pause and continue. It calls the OnContinue virtual + function in which you can specify the actions to take when the service + continues. If an error occurs, the error will be logged in the + Application event log, and the service will still be paused. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +CServiceBase::Continue() +{ + try + { + // + // Tell SCM that the service is resuming. + // + SetServiceStatus(SERVICE_CONTINUE_PENDING); + + // + // Perform service-specific continue operations. + // + OnContinue(); + + // + // Tell SCM that the service is running. + // + SetServiceStatus(SERVICE_RUNNING); + } + catch (DWORD Error) + { + // + // Log the error. + // + WriteToErrorLog(L"Service Continue", Error); + + // + // Tell SCM that the service is still paused. + // + SetServiceStatus(SERVICE_PAUSED); + } + catch (...) + { + // + // Log the error. + // + WriteToEventLog(L"Service failed to resume.", EVENTLOG_ERROR_TYPE); + + // + // Tell SCM that the service is still paused. + // + SetServiceStatus(SERVICE_PAUSED); + } +} + + +/*++ + +Routine Description: + + When implemented in a derived class, OnContinue runs when a + Continue command is sent to the service by the SCM. Specifies actions to + take when a service resumes normal functioning after being paused. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +CServiceBase::OnContinue() +{ +} + + +/*++ + +Routine Description: + + The function executes when the system is shutting down. It + calls the OnShutdown virtual function in which you can specify what + should occur immediately prior to the system shutting down. If an error + occurs, the error will be logged in the Application event log. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +CServiceBase::Shutdown() +{ + try + { + // + // Perform service-specific shutdown operations. + // + OnShutdown(); + + // + // Tell SCM that the service is stopped. + // + SetServiceStatus(SERVICE_STOPPED); + } + catch (DWORD Error) + { + // + // Log the error. + // + WriteToErrorLog(L"Service Shutdown", Error); + } + catch (...) + { + // + // Log the error. + // + WriteToEventLog(L"Service failed to shut down.", EVENTLOG_ERROR_TYPE); + } +} + + +/*++ + +Routine Description: + + When implemented in a derived class, executes when the system + is shutting down. Specifies what should occur immediately prior to the + system shutting down. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +CServiceBase::OnShutdown() +{ +} + +#pragma endregion + + +#pragma region Helper Functions + +/*++ + +Routine Description: + + The function sets the service status and reports the status to the SCM. + +Arguments: + + CurrentState - The current state of the service + + Win32ExitCode - The error code to report + + WaitHint - The estimated time for pending operation, in milliseconds + +Return Value: + + VOID + +--*/ +VOID +CServiceBase::SetServiceStatus( + DWORD CurrentState, + DWORD Win32ExitCode, + DWORD WaitHint + ) +{ + static DWORD CheckPoint = 1; + + // + // Fill in the SERVICE_STATUS structure of the service. + // + + m_status.dwCurrentState = CurrentState; + m_status.dwWin32ExitCode = Win32ExitCode; + m_status.dwWaitHint = WaitHint; + + m_status.dwCheckPoint = ((CurrentState == SERVICE_RUNNING) || + (CurrentState == SERVICE_STOPPED)) ? 0 : + CheckPoint++; + + // + // Report the status of the service to the SCM. + // + ::SetServiceStatus(m_statusHandle, &m_status); +} + +#pragma endregion
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/ServiceBase.h b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/ServiceBase.h new file mode 100644 index 00000000..106597e1 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/ServiceBase.h @@ -0,0 +1,423 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + ServiceBase.cpp + +Abstract: + + Provides a base class for a service that will exist as part of a service + application. CServiceBase must be derived from when creating a new service + class. + +Environment: + + User mode + +--*/ + +#pragma once + +#include <windows.h> +#include "Utils.h" + +class CServiceBase +{ +public: + + /*++ + + Routine Description: + + Register the executable for a service with the Service Control + Manager (SCM). After you call Run(ServiceBase), the SCM issues a Start + command, which results in a call to the OnStart method in the service. + This method blocks until the service has stopped. + + Arguments: + + Service - The reference to a CServiceBase object. It will become the + singleton service instance of this service application. + + Return Value: + + If the function succeeds, the return value is TRUE. If the function + fails, the return value is FALSE. To get extended error information, + call GetLastError. + + --*/ + static BOOL Run(CServiceBase &service); + + + /*++ + + Routine Description: + + The constructor of CServiceBase. It initializes a new instance + of the CServiceBase class. The optional parameters (CanStop, + CanShutdown and CanPauseContinue) allow you to specify whether the + service can be stopped, paused and continued, or be notified when system + shutdown occurs. + + Arguments: + + ServiceName - The name of the service + + CanStop - The service can be stopped + + CanShutdown - The service is notified when system shutdown occurs + + CanPauseContinue - The service can be paused and continued + + Return Value: + + VOID + + --*/ + CServiceBase(PWSTR ServiceName, + BOOL CanStop = TRUE, + BOOL CanShutdown = TRUE, + BOOL CanPauseContinue = FALSE); + + + /*++ + + Routine Description: + + The virtual destructor of CServiceBase. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + virtual ~CServiceBase(); + + + /*++ + + Routine Description: + + This function stops the service. It calls the OnStop virtual + function in which you can specify the actions to take when the service + stops. If an error occurs, the error will be logged in the Application + event log, and the service will be restored to the original state. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + VOID Stop(); + +protected: + + /*++ + + Routine Description: + + When implemented in a derived class, executes when a Start + command is sent to the service by the SCM or when the operating system + starts (for a service that starts automatically). Specifies actions to + take when the service starts. Be sure to periodically call + CServiceBase::SetServiceStatus() with SERVICE_START_PENDING if the + procedure is going to take long time. You may also consider spawning a + new thread in OnStart to perform time-consuming initialization tasks. + + Arguments: + + Argc - The number of command line arguments + + Argv - The array of command line arguments + + Return Value: + + VOID + + --*/ + virtual VOID OnStart(DWORD Argc, PWSTR *Argv); + + + /*++ + + Routine Description: + + When implemented in a derived class, executes when a Stop + command is sent to the service by the SCM. Specifies actions to take + when a service stops running. Be sure to periodically call + CServiceBase::SetServiceStatus() with SERVICE_STOP_PENDING if the + procedure is going to take long time. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + virtual VOID OnStop(); + + + /*++ + + Routine Description: + + When implemented in a derived class, executes when a Pause + command is sent to the service by the SCM. Specifies actions to take + when a service pauses. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + virtual VOID OnPause(); + + + /*++ + + Routine Description: + + When implemented in a derived class, OnContinue runs when a + Continue command is sent to the service by the SCM. Specifies actions to + take when a service resumes normal functioning after being paused. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + virtual VOID OnContinue(); + + + /*++ + + Routine Description: + + When implemented in a derived class, executes when the system + is shutting down. Specifies what should occur immediately prior to the + system shutting down. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + virtual VOID OnShutdown(); + + + /*++ + + Routine Description: + + The function sets the service status and reports the status to the SCM. + + Arguments: + + CurrentState - The current state of the service + + Win32ExitCode - The error code to report + + WaitHint - The estimated time for pending operation, in milliseconds + + Return Value: + + VOID + + --*/ + VOID SetServiceStatus(DWORD CurrentState, + DWORD Win32ExitCode = NO_ERROR, + DWORD WaitHint = 0); + +private: + + /*++ + + Routine Description: + + The entry point for the service. It registers the handler function + for the service and starts the service. + + Arguments: + + Argc - The number of command line arguments + + Argv - The array of command line arguments + + Return Value: + + VOID + + --*/ + static VOID WINAPI ServiceMain(DWORD Argc, PWSTR *Argv); + + + /*++ + + Routine Description: + + Called by the SCM whenever a control code is sent to the service. + + Arguments: + + CtrlCode - The control code. This parameter can be one of + the following values: + + SERVICE_CONTROL_CONTINUE + SERVICE_CONTROL_INTERROGATE + SERVICE_CONTROL_NETBINDADD + SERVICE_CONTROL_NETBINDDISABLE + SERVICE_CONTROL_NETBINDREMOVE + SERVICE_CONTROL_PARAMCHANGE + SERVICE_CONTROL_PAUSE + SERVICE_CONTROL_SHUTDOWN + SERVICE_CONTROL_STOP + + This parameter can also be a user-defined control + code ranging from 128 to 255. + + Return Value: + + VOID + + --*/ + static VOID WINAPI ServiceCtrlHandler(DWORD Ctrl); + + + /*++ + + Routine Description: + + This function starts the service. It calls the OnStart virtual function + in which you can specify the actions to take when the service starts. If + an error occurs during the startup, the error will be logged in the + Application event log, and the service will be stopped. + + Arguments: + + Argc - The number of command line arguments + + Argv - The array of command line arguments + + Return Value: + + VOID + + --*/ + VOID Start(DWORD Argc, PWSTR *Argv); + + + /*++ + + Routine Description: + + The function pauses the service if the service supports pause + and continue. It calls the OnPause virtual function in which you can + specify the actions to take when the service pauses. If an error occurs, + the error will be logged in the Application event log, and the service + will become running. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + VOID Pause(); + + + /*++ + + Routine Description: + + The function resumes normal functioning after being paused if + the service supports pause and continue. It calls the OnContinue virtual + function in which you can specify the actions to take when the service + continues. If an error occurs, the error will be logged in the + Application event log, and the service will still be paused. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + VOID Continue(); + + + /*++ + + Routine Description: + + The function executes when the system is shutting down. It + calls the OnShutdown virtual function in which you can specify what + should occur immediately prior to the system shutting down. If an error + occurs, the error will be logged in the Application event log. + + Arguments: + + VOID + + Return Value: + + VOID + + --*/ + VOID Shutdown(); + + + // + // The singleton service instance. + // + static CServiceBase *s_service; + + // + // The name of the service. + // + PWSTR m_name; + + // + // The status of the service. + // + SERVICE_STATUS m_status; + + // + // The service status handle. + // + SERVICE_STATUS_HANDLE m_statusHandle; +};
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/ThreadPool.h b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/ThreadPool.h new file mode 100644 index 00000000..3d851537 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/ThreadPool.h @@ -0,0 +1,80 @@ +/****************************** Module Header ******************************\ +* Module Name: ThreadPool.h +* Project: CppWindowsService +* Copyright (c) Microsoft Corporation. +* +* The class was designed by Kenny Kerr. It provides the ability to queue +* simple member functions of a class to the Windows thread pool. +* +* Using the thread pool is simple and feels natural in C++. +* +* class CSampleService +* { +* public: +* +* void AsyncRun() +* { +* CThreadPool::QueueUserWorkItem(&Service::Run, this); +* } +* +* void Run() +* { +* // Some lengthy operation +* } +* }; +* +* Kenny Kerr spends most of his time designing and building distributed +* applications for the Microsoft Windows platform. He also has a particular +* passion for C++ and security programming. Reach Kenny at +* http://weblogs.asp.net/kennykerr/ or visit his Web site: +* http://www.kennyandkarin.com/Kenny/. +* +* This source is subject to the Microsoft Public License. +* See http://www.microsoft.com/en-us/openness/resources/licenses.aspx#MPL. +* All other rights reserved. +* +* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, +* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. +\***************************************************************************/ + +#pragma once + +#include <memory> + + +class CThreadPool +{ +public: + + template <typename T> + static void QueueUserWorkItem(void (T::*function)(void), + T *object, ULONG flags = WT_EXECUTELONGFUNCTION) + { + typedef std::pair<void (T::*)(), T *> CallbackType; + std::auto_ptr<CallbackType> p(new CallbackType(function, object)); + + if (::QueueUserWorkItem(ThreadProc<T>, p.get(), flags)) + { + // The ThreadProc now has the responsibility of deleting the pair. + p.release(); + } + else + { + throw GetLastError(); + } + } + +private: + + template <typename T> + static DWORD WINAPI ThreadProc(PVOID context) + { + typedef std::pair<void (T::*)(), T *> CallbackType; + + std::auto_ptr<CallbackType> p(static_cast<CallbackType *>(context)); + + (p->second->*p->first)(); + return 0; + } +};
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Utils.cpp b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Utils.cpp new file mode 100644 index 00000000..e8fc87ee --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Utils.cpp @@ -0,0 +1,156 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + Utils.cpp + +Abstract: + + Provides utility function to SampleApp.cpp. + +Environment: + + User mode + +--*/ + +#include "Utils.h" + +// +// Service trace event provider +// {54a25c42-cd91-4210-98cc-c3447b56e447} +// +EXTERN_C __declspec(selectany) const GUID SERVICE_PROVIDER_GUID = { 0x54a25c42, 0xcd91, 0x4210,{ 0x98, 0xcc, 0xc3, 0x44, 0x7b, 0x56, 0xe4, 0x47 } }; + +REGHANDLE m_etwRegHandle; + + +/*++ + +Routine Description: + + Sets up logging. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +SetupEvents() +{ + NTSTATUS status = EventRegister(&SERVICE_PROVIDER_GUID, + nullptr, + nullptr, + &m_etwRegHandle); + + if (status != ERROR_SUCCESS) + { + wprintf(L"Provider not registered. EventRegister failed with error: 0x%08X\n", status); + } +} + + +/*++ + +Routine Description: + + Destroys logging. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID +DestroyEvents() +{ + if (m_etwRegHandle != NULL) + { + EventUnregister(m_etwRegHandle); + } +} + + +/*++ + +Routine Description: + + Log a message. + +Arguments: + + Message - The string message to be logged + + Level - The type of event to be logged. This parameter can + be one of the following values: + + TRACE_LEVEL_CRITICAL + TRACE_LEVEL_ERROR + TRACE_LEVEL_WARNING + TRACE_LEVEL_INFORMATION + TRACE_LEVEL_VERBOSE + +Return Value: + + VOID + +--*/ +VOID +WriteToEventLog( + PWSTR Message, + BYTE Level + ) +{ + if (m_etwRegHandle != NULL) + { + EventWriteString(m_etwRegHandle, Level, 0, Message); + } +} + + +/*++ + +Routine Description: + + Log an error message. + +Arguments: + + Function - The function that gives the error + + Error - The error code + +Return Value: + + VOID + +--*/ +VOID +WriteToErrorLog( + PWSTR Function, + DWORD Error + ) +{ + WCHAR Message[260]; + + StringCchPrintf(Message, ARRAYSIZE(Message), + L"%ws failed with error: 0x%08x", Function, Error); + + WriteToEventLog(Message, TRACE_LEVEL_ERROR); +}
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Utils.h b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Utils.h new file mode 100644 index 00000000..b619f461 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/Utils.h @@ -0,0 +1,111 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + Utils.cpp + +Abstract: + + Provides utility function to SampleApp.cpp. + +Environment: + + User mode + +--*/ + +#pragma once + +#include <Windows.h> +#include <strsafe.h> +#include <evntprov.h> +#include <evntrace.h> + +/*++ + +Routine Description: + + Sets up logging. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID SetupEvents(); + + +/*++ + +Routine Description: + + Destroys logging. + +Arguments: + + VOID + +Return Value: + + VOID + +--*/ +VOID DestroyEvents(); + + +/*++ + +Routine Description: + + Log a message. + +Arguments: + + Message - The string message to be logged + + Level - The type of event to be logged. This parameter can + be one of the following values: + + TRACE_LEVEL_CRITICAL + TRACE_LEVEL_ERROR + TRACE_LEVEL_WARNING + TRACE_LEVEL_INFORMATION + TRACE_LEVEL_VERBOSE + +Return Value: + + VOID + +--*/ +VOID WriteToEventLog(PWSTR Message, BYTE Level); + + +/*++ + +Routine Description: + + Log an error message. + +Arguments: + + Function - The function that gives the error + + Error - The error code + +Return Value: + + VOID + +--*/ +VOID WriteToErrorLog(PWSTR Function, DWORD Error);
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/osrfx2_DCHU_usersvc.filters b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/osrfx2_DCHU_usersvc.filters new file mode 100644 index 00000000..7f12a302 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/osrfx2_DCHU_usersvc.filters @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Source Files"> + <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> + <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> + </Filter> + <Filter Include="Header Files"> + <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> + <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> + </Filter> + <Filter Include="Resource Files"> + <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> + <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions> + </Filter> + </ItemGroup> + <ItemGroup> + <ClCompile Include="SampleService.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="ServiceBase.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="Utils.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="Main.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="CppWindowsService.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + </ItemGroup> + <ItemGroup> + <ClInclude Include="SampleService.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="ServiceBase.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="ThreadPool.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="Utils.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="Main.h"> + <Filter>Header Files</Filter> + </ClInclude> + </ItemGroup> + <ItemGroup> + <None Include="Documentation\ReadMe.htm" /> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/osrfx2_DCHU_usersvc.inx b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/osrfx2_DCHU_usersvc.inx Binary files differnew file mode 100644 index 00000000..61e1e958 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/osrfx2_DCHU_usersvc.inx diff --git a/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/osrfx2_DCHU_usersvc.vcxproj b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/osrfx2_DCHU_usersvc.vcxproj new file mode 100644 index 00000000..8547d303 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_base/osrfx2_DCHU_usersvc/osrfx2_DCHU_usersvc.vcxproj @@ -0,0 +1,206 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{DE70E2D1-6A4D-4984-BD82-CE750889F0D3}</ProjectGuid> + <RootNamespace>osrfx2_DCHU_usersvc</RootNamespace> + <Keyword>Win32Proj</Keyword> + <ProjectName>osrfx2_DCHU_usersvc</ProjectName> + <WindowsTargetPlatformVersion>10.0.15063.0</WindowsTargetPlatformVersion> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <CharacterSet>Unicode</CharacterSet> + <WholeProgramOptimization>true</WholeProgramOptimization> + <PlatformToolset>v140</PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <CharacterSet>Unicode</CharacterSet> + <PlatformToolset>v140</PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <CharacterSet>Unicode</CharacterSet> + <WholeProgramOptimization>false</WholeProgramOptimization> + <PlatformToolset>v140</PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <CharacterSet>Unicode</CharacterSet> + <PlatformToolset>v140</PlatformToolset> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup> + <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion> + <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> + <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir> + <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental> + <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> + <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir> + <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental> + <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> + <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir> + <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental> + <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> + <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir> + <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental> + <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet> + <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> + <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> + <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet> + <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" /> + <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" /> + <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet> + <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> + <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> + <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet> + <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" /> + <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" /> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <Optimization>Full</Optimization> + <PreprocessorDefinitions>WIN32;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <MinimalRebuild>true</MinimalRebuild> + <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + <PrecompiledHeader> + </PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <DebugInformationFormat>EditAndContinue</DebugInformationFormat> + </ClCompile> + <Link> + <GenerateDebugInformation>true</GenerateDebugInformation> + <SubSystem>Console</SubSystem> + <TargetMachine>MachineX86</TargetMachine> + <AdditionalDependencies>onecoreuap.lib;%(AdditionalDependencies);</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <ClCompile> + <Optimization>Full</Optimization> + <IntrinsicFunctions>true</IntrinsicFunctions> + <PreprocessorDefinitions>WIN32;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + <FunctionLevelLinking>true</FunctionLevelLinking> + <PrecompiledHeader> + </PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> + </ClCompile> + <Link> + <GenerateDebugInformation>true</GenerateDebugInformation> + <SubSystem>Console</SubSystem> + <OptimizeReferences>true</OptimizeReferences> + <EnableCOMDATFolding>true</EnableCOMDATFolding> + <TargetMachine>MachineX86</TargetMachine> + <AdditionalDependencies>onecoreuap.lib;%(AdditionalDependencies);</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Midl> + <TargetEnvironment>X64</TargetEnvironment> + </Midl> + <ClCompile> + <Optimization>Full</Optimization> + <PreprocessorDefinitions>WIN32;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <MinimalRebuild>true</MinimalRebuild> + <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + <PrecompiledHeader> + </PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> + </ClCompile> + <Link> + <GenerateDebugInformation>true</GenerateDebugInformation> + <SubSystem>Console</SubSystem> + <TargetMachine>MachineX64</TargetMachine> + <AdditionalDependencies>onecoreuap.lib;%(AdditionalDependencies);</AdditionalDependencies> + <IgnoreAllDefaultLibraries> + </IgnoreAllDefaultLibraries> + <IgnoreSpecificDefaultLibraries> + </IgnoreSpecificDefaultLibraries> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Midl> + <TargetEnvironment>X64</TargetEnvironment> + </Midl> + <ClCompile> + <Optimization>Full</Optimization> + <IntrinsicFunctions>true</IntrinsicFunctions> + <PreprocessorDefinitions>WIN32;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + <FunctionLevelLinking>true</FunctionLevelLinking> + <PrecompiledHeader> + </PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> + </ClCompile> + <Link> + <GenerateDebugInformation>true</GenerateDebugInformation> + <SubSystem>Console</SubSystem> + <OptimizeReferences>true</OptimizeReferences> + <EnableCOMDATFolding>true</EnableCOMDATFolding> + <TargetMachine>MachineX64</TargetMachine> + <AdditionalDependencies>onecoreuap.lib;%(AdditionalDependencies);</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemGroup> + <ClCompile Include="CppWindowsService.cpp" /> + <ClCompile Include="SampleService.cpp" /> + <ClCompile Include="ServiceBase.cpp" /> + <ClCompile Include="Main.cpp" /> + <ClCompile Include="Utils.cpp" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="SampleService.h" /> + <ClInclude Include="ServiceBase.h" /> + <ClInclude Include="Main.h" /> + <ClInclude Include="ThreadPool.h" /> + <ClInclude Include="Utils.h" /> + </ItemGroup> + <ItemGroup> + <None Include="Documentation\ReadMe.htm"> + <DeploymentContent>true</DeploymentContent> + </None> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.filters b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.filters new file mode 100644 index 00000000..fa953f4c --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.filters @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Driver Files"> + <UniqueIdentifier>{8E41214B-6785-4CFE-B992-037D68949A14}</UniqueIdentifier> + <Extensions>inf;inv;inx;mof;mc;</Extensions> + </Filter> + </ItemGroup> + <ItemGroup> + <Inf Include="osrfx2_DCHU_component.inx"> + <Filter>Driver Files</Filter> + </Inf> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.inx b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.inx new file mode 100644 index 00000000..8baab1a0 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.inx @@ -0,0 +1,64 @@ +;/*++ +; +;Copyright (c) Microsoft Corporation. All rights reserved. +; +; THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY +; KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +; IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR +; PURPOSE. +; +;Module Name: +; +; osrfx2_DCHU_component.INF +; +;Abstract: +; +; Installation inf for one of the OSR FX2 Learning Kit's +; AddComponent directives +; +;--*/ + +[Version] +Signature = "$Windows NT$" +Class = SoftwareComponent +ClassGuid = {5c4c3332-344d-483c-8739-259e934c9cc8} +Provider = %ManufacturerName% +CatalogFile = osrfx2_DCHU_component.cat + +[Manufacturer] +%ManufacturerName% = OsrFx2Component, NT$ARCH$ + +[OsrFx2Component.NT$ARCH$] +%DeviceName% = OsrFx2Component_Install, SWC\VID_045e&PID_94ab + +[SourceDisksFiles] +osrfx2_DCHU_componentsoftware.exe = 1 + +[SourceDisksNames] +1 = %DiskName% + +[DestinationDirs] +OsrFx2Component_CopyFiles = 13 ; copy to driverstore + +[OsrFx2Component_Install.NT] +CopyFiles = OsrFx2Component_CopyFiles + +[OsrFx2Component_Install.NT.Services] +AddService = , 0x00000002 + +[OsrFx2Component_Install.NT.Software] +AddSoftware = osrfx2_DCHU_componentsoftware,, OsrFx2Component_SoftwareInstall + +[OsrFx2Component_SoftwareInstall] +SoftwareType = 1 +SoftwareBinary = osrfx2_DCHU_componentsoftware.exe +SoftwareArguments = <<DeviceInstanceId>> +SoftwareVersion = 1.0.0.0 + +[OsrFx2Component_CopyFiles] +osrfx2_DCHU_componentsoftware.exe + +[Strings] +ManufacturerName = "Contoso" +DiskName = "OsrFx2 DCHU Component Installation Disk" +DeviceName = "OsrFx2 DCHU Component Device"
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.vcxproj b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.vcxproj new file mode 100644 index 00000000..bc19d287 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_component/osrfx2_DCHU_component.vcxproj @@ -0,0 +1,276 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|ARM"> + <Configuration>Debug</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM"> + <Configuration>Release</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|ARM64"> + <Configuration>Debug</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM64"> + <Configuration>Release</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + </ItemGroup> + <ItemGroup> + <Inf Include="osrfx2_DCHU_component.inx" /> + </ItemGroup> + <ItemGroup> + <FilesToPackage Include="$(SolutionDir)$(Platform)\$(Configuration)\osrfx2_DCHU_componentsoftware.exe" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <FilesToPackage Include="$(SolutionDir)$(Platform)\$(ConfigurationName)\osrfx2_DCHU_componentsoftware.exe" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <FilesToPackage Include="$(SolutionDir)\$(Configuration)\osrfx2_DCHU_componentsoftware.exe" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + <FilesToPackage Include="$(SolutionDir)\$(ConfigurationName)\osrfx2_DCHU_componentsoftware.exe" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{F90EFA96-B075-4531-B4E1-F406362D16BF}</ProjectGuid> + <TemplateGuid>{4605da2c-74a5-4865-98e1-152ef136825f}</TemplateGuid> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion> + <Configuration>Debug</Configuration> + <Platform Condition="'$(Platform)' == ''">Win32</Platform> + <RootNamespace>osrfx2_DCHU_component</RootNamespace> + <ProjectName>osrfx2_DCHU_component</ProjectName> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Inf> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.cpp b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.cpp new file mode 100644 index 00000000..c14e66d1 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.cpp @@ -0,0 +1,489 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + osrfx2_DCHU_componentsoftware.cpp + +Abstract: + + An example .exe to run using the AddSoftware directive within an INF. + Contains an example on how to obtain a handle to the primary device using + SoftwareArguments within an AddSoftware directive's section. + +Environment: + + User mode + +--*/ + +#include "stdafx.h" + +#define BUFFER_SIZE (128 * sizeof(WCHAR)) +#define DEVICE_REG_SUBKEY L"OSR" +#define DEVICE_VALUE_OP_MODE L"OperatingMode" +#define DEVICE_VALUE_OP_PARAMS L"OperatingParams" +#define DEVICE_VALUE_OP_EXCEPTIONS L"OperatingExceptions" +#define CONTOSO_FILEPATH L"C:\\Program Files\\Contoso" +#define OSRFX2_DCHU_FILEPATH L"C:\\Program Files\\Contoso\\OsrFx2_DCHU" +#define FILEPATH L"C:\\Program Files\\Contoso\\OsrFx2_DCHU\\AddSoftwareInstallationFile.txt" +#define FILE_CONTENT L"Operating Mode: %ws\r\nOperating Params: %ws\r\nOperating Exceptions: %ws" + + +/*++ + +Routine Description: + +Arguments: + +Return Value: + + +--*/ +DWORD +WriteToFile( + _In_ PWSTR MessageText, + _In_ DWORD MessageTextLength + ) +{ + DWORD Err = ERROR_SUCCESS; + BOOL ErrorFlag = FALSE; + HANDLE hFile = INVALID_HANDLE_VALUE; + DWORD BytesToWrite; + DWORD BytesWritten; + + if (!CreateDirectory(CONTOSO_FILEPATH, NULL)) + { + Err = GetLastError(); + + if (Err == ERROR_ALREADY_EXISTS) + { + Err = ERROR_SUCCESS; + } + else + { + goto cleanup; + } + } + + if (!CreateDirectory(OSRFX2_DCHU_FILEPATH, NULL)) + { + Err = GetLastError(); + + if (Err == ERROR_ALREADY_EXISTS) + { + Err = ERROR_SUCCESS; + } + else + { + goto cleanup; + } + } + + hFile = CreateFile(FILEPATH, + GENERIC_WRITE, + 0, + NULL, + OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); + + if (hFile == INVALID_HANDLE_VALUE) + { + Err = ERROR_INVALID_PARAMETER; + goto cleanup; + } + + BytesToWrite = MessageTextLength * sizeof(WCHAR); + + ErrorFlag = WriteFile(hFile, + MessageText, + BytesToWrite, + &BytesWritten, + NULL); + + if ((!ErrorFlag) || + (BytesToWrite != BytesWritten)) + { + Err = GetLastError(); + goto cleanup; + } + +cleanup: + + if (hFile != INVALID_HANDLE_VALUE) + { + CloseHandle(hFile); + } + + return Err; +} + + +/*++ + +Routine Description: + + Obtains the handle to the device that used a separate Software Component + INF to install software. + +Arguments: + + Argc - The number of command line arguments + + Argv - The array of command line arguments + +Return Value: + + VOID + +--*/ +VOID +__cdecl +_tmain( + INT Argc, + TCHAR *Argv[]) +{ + DWORD Err = ERROR_SUCCESS; + HRESULT hr = S_OK; + BOOL ErrorFlag = FALSE; + DWORD BytesToWrite = 0; + DWORD BytesWritten = 0; + PTSTR DeviceInstanceId; + HDEVINFO DevInfoList = INVALID_HANDLE_VALUE; + SP_DEVINFO_DATA DevInfoData; + WCHAR ParentDeviceInstanceId[MAX_DEVICE_ID_LEN]; + DWORD RequiredSize; + DEVPROPTYPE DevPropType; + SP_DEVINFO_DATA ParentDevInfoData; + HKEY DevRegKey = NULL; + PWSTR OperatingMode = NULL; + PWSTR OperatingParams = NULL; + PWSTR OperatingExceptions = NULL; + DWORD ValueType; + DWORD ValueSize = BUFFER_SIZE; + HKEY DevOsrRegKey = NULL; + PWSTR FileText = NULL; + DWORD FileTextLength; + + // + // Validate arguments. + // + if (Argc != 2) + { + Err = ERROR_INVALID_PARAMETER; + goto cleanup; + } + + OperatingMode = (PWSTR)malloc(BUFFER_SIZE * sizeof(WCHAR)); + + if (OperatingMode == NULL) + { + Err = ERROR_OUTOFMEMORY; + goto cleanup; + } + + OperatingParams = (PWSTR)malloc(BUFFER_SIZE * sizeof(WCHAR)); + + if (OperatingParams == NULL) + { + Err = ERROR_OUTOFMEMORY; + goto cleanup; + } + + OperatingExceptions = (PWSTR)malloc(BUFFER_SIZE * sizeof(WCHAR)); + + if (OperatingExceptions == NULL) + { + Err = ERROR_OUTOFMEMORY; + goto cleanup; + } + + // + // Argv[1] should be the device instance ID. + // + DeviceInstanceId = Argv[1]; + + // + // Create a device info list to store queried device handles. + // + DevInfoList = SetupDiCreateDeviceInfoList(NULL, NULL); + + if (DevInfoList == INVALID_HANDLE_VALUE) + { + Err = ERROR_OUTOFMEMORY; + goto cleanup; + } + + DevInfoData.cbSize = sizeof(SP_DEVINFO_DATA); + + // + // Add the Software Component device that called AddSoftware to the + // device info list, which will be used to find the primary device that + // called AddComponent in the first place. + // + if (!SetupDiOpenDeviceInfo(DevInfoList, + DeviceInstanceId, + NULL, + 0, + &DevInfoData)) + { + Err = GetLastError(); + goto cleanup; + } + + // + // Get the device instance id of the opened device's parent. + // + if (!SetupDiGetDeviceProperty(DevInfoList, + &DevInfoData, + &DEVPKEY_Device_Parent, + &DevPropType, + (PBYTE)ParentDeviceInstanceId, + sizeof(ParentDeviceInstanceId), + &RequiredSize, + 0)) + { + Err = GetLastError(); + goto cleanup; + } + + if ((DevPropType != DEVPROP_TYPE_STRING) || + (RequiredSize < sizeof(WCHAR))) + { + Err = ERROR_INVALID_PARAMETER; + goto cleanup; + } + + ParentDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA); + + // + // Get the parent of the device we retrieved first, which is the device + // that called AddComponent in its INF. + // + if (!SetupDiOpenDeviceInfoW(DevInfoList, + ParentDeviceInstanceId, + NULL, + 0, + &ParentDevInfoData)) + { + Err = GetLastError(); + goto cleanup; + } + + // + // Open up the HW registry keys of the primary device. + // + DevRegKey = SetupDiOpenDevRegKey(DevInfoList, + &ParentDevInfoData, + DICS_FLAG_GLOBAL, + 0, + DIREG_DEV, + KEY_READ); + + if (DevRegKey == INVALID_HANDLE_VALUE) + { + Err = GetLastError(); + DevRegKey = NULL; + goto cleanup; + } + + Err = RegOpenKeyEx(DevRegKey, + DEVICE_REG_SUBKEY, + 0, + KEY_QUERY_VALUE, + &DevOsrRegKey); + + if (Err != ERROR_SUCCESS) + { + goto cleanup; + } + + // + // Retrieve the registry values defined in the primary device's INF. + // Note that if the extension INF was applied, the extension INF would + // overwrite OperatingParams and create OperatingExceptions. + // + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_MODE, + NULL, + &ValueType, + (LPBYTE)OperatingMode, + &ValueSize); + + while (Err == ERROR_MORE_DATA) + { + // + // Create a larger buffer. + // + OperatingMode = (PTSTR)realloc(OperatingMode, ValueSize); + + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_MODE, + NULL, + &ValueType, + (LPBYTE)OperatingMode, + &ValueSize); + } + + if (Err != ERROR_SUCCESS) + { + OperatingMode[0] = TEXT('\0'); + } + else if ((ValueType != REG_SZ) || + (ValueSize < sizeof(TCHAR))) + { + Err = ERROR_REGISTRY_CORRUPT; + OperatingMode[0] = TEXT('\0'); + } + + ValueSize = BUFFER_SIZE; + + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_PARAMS, + NULL, + &ValueType, + (LPBYTE)OperatingParams, + &ValueSize); + + while (Err == ERROR_MORE_DATA) + { + // + // Create a larger buffer. + // + OperatingParams = (PTSTR)realloc(OperatingParams, ValueSize); + + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_MODE, + NULL, + &ValueType, + (LPBYTE)OperatingParams, + &ValueSize); + } + + if (Err != ERROR_SUCCESS) + { + OperatingParams[0] = TEXT('\0'); + } + else if ((ValueType != REG_SZ) || + (ValueSize < sizeof(TCHAR))) + { + Err = ERROR_REGISTRY_CORRUPT; + OperatingParams[0] = TEXT('\0'); + } + + ValueSize = BUFFER_SIZE; + + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_EXCEPTIONS, + NULL, + &ValueType, + (LPBYTE)OperatingExceptions, + &ValueSize); + + while (Err == ERROR_MORE_DATA) + { + // + // Create a larger buffer. + // + OperatingExceptions = (PTSTR)realloc(OperatingExceptions, ValueSize); + + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_EXCEPTIONS, + NULL, + &ValueType, + (LPBYTE)OperatingExceptions, + &ValueSize); + } + + if (Err != ERROR_SUCCESS) + { + OperatingExceptions[0] = TEXT('\0'); + } + else if ((ValueType != REG_SZ) || + (ValueSize < sizeof(TCHAR))) + { + Err = ERROR_REGISTRY_CORRUPT; + OperatingExceptions[0] = TEXT('\0'); + } + + FileTextLength = (DWORD)wcslen(OperatingMode) + + (DWORD)wcslen(OperatingParams) + + (DWORD)wcslen(OperatingExceptions) + + (DWORD)wcslen(FILE_CONTENT) - + 9; // Subtract the 3 %ws + + FileText = (PWSTR)malloc((FileTextLength + 1) * sizeof(WCHAR)); + + if (FileText == NULL) + { + Err = ERROR_OUTOFMEMORY; + goto cleanup; + } + + hr = StringCchPrintf(FileText, + FileTextLength + 1, + FILE_CONTENT, + OperatingMode, + OperatingParams, + OperatingExceptions); + + if (FAILED(hr)) + { + Err = HRESULT_CODE(hr); + goto cleanup; + } + + Err = WriteToFile(FileText, FileTextLength); + + if (Err != ERROR_SUCCESS) + { + goto cleanup; + } + +cleanup: + + if (FileText != NULL) + { + free(FileText); + } + + if (OperatingExceptions != NULL) + { + free(OperatingExceptions); + } + + if (OperatingParams != NULL) + { + free(OperatingParams); + } + + if (OperatingMode != NULL) + { + free(OperatingMode); + } + + if (DevOsrRegKey != NULL) + { + RegCloseKey(DevOsrRegKey); + } + + if (DevRegKey != NULL) + { + RegCloseKey(DevRegKey); + } + + if (DevInfoList != INVALID_HANDLE_VALUE) + { + SetupDiDestroyDeviceInfoList(DevInfoList); + } + + return; +} + diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.filters b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.filters new file mode 100644 index 00000000..395438fa --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.filters @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Source Files"> + <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> + <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> + </Filter> + <Filter Include="Header Files"> + <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> + <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions> + </Filter> + <Filter Include="Resource Files"> + <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> + <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> + </Filter> + </ItemGroup> + <ItemGroup> + <Text Include="ReadMe.txt" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="stdafx.h"> + <Filter>Header Files</Filter> + </ClInclude> + </ItemGroup> + <ItemGroup> + <ClCompile Include="stdafx.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="osrfx2_DCHU_componentsoftware.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.vcxproj b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.vcxproj new file mode 100644 index 00000000..931646bb --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.vcxproj @@ -0,0 +1,169 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{26D91630-B8FF-4102-A258-32F7D1C84E20}</ProjectGuid> + <Keyword>Win32Proj</Keyword> + <RootNamespace>osrfx2_DCHU_componentsoftware</RootNamespace> + <WindowsTargetPlatformVersion>10.0.15063.0</WindowsTargetPlatformVersion> + <ProjectName>osrfx2_DCHU_componentsoftware</ProjectName> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>v140</PlatformToolset> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>v140</PlatformToolset> + <WholeProgramOptimization>false</WholeProgramOptimization> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>v140</PlatformToolset> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>v140</PlatformToolset> + <WholeProgramOptimization>false</WholeProgramOptimization> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="Shared"> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <LinkIncremental>true</LinkIncremental> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <LinkIncremental>true</LinkIncremental> + <TargetName>$(ProjectName)</TargetName> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <LinkIncremental>false</LinkIncremental> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <LinkIncremental>false</LinkIncremental> + <TargetName>$(ProjectName)</TargetName> + <TargetExt>.exe</TargetExt> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <PrecompiledHeader>Use</PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <Optimization>Disabled</Optimization> + <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;setupapi.lib;</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <PrecompiledHeader>Use</PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <Optimization>Disabled</Optimization> + <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;setupapi.lib;</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <ClCompile> + <WarningLevel>Level3</WarningLevel> + <PrecompiledHeader>Use</PrecompiledHeader> + <Optimization>MaxSpeed</Optimization> + <FunctionLevelLinking>true</FunctionLevelLinking> + <IntrinsicFunctions>true</IntrinsicFunctions> + <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <EnableCOMDATFolding>true</EnableCOMDATFolding> + <OptimizeReferences>true</OptimizeReferences> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;setupapi.lib;</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <WarningLevel>Level3</WarningLevel> + <PrecompiledHeader>Use</PrecompiledHeader> + <Optimization>MaxSpeed</Optimization> + <FunctionLevelLinking>true</FunctionLevelLinking> + <IntrinsicFunctions>true</IntrinsicFunctions> + <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <EnableCOMDATFolding>true</EnableCOMDATFolding> + <OptimizeReferences>true</OptimizeReferences> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;setupapi.lib;</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemGroup> + <Text Include="ReadMe.txt" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="stdafx.h" /> + </ItemGroup> + <ItemGroup> + <ClCompile Include="osrfx2_DCHU_componentsoftware.cpp" /> + <ClCompile Include="stdafx.cpp"> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader> + </ClCompile> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/stdafx.cpp b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/stdafx.cpp new file mode 100644 index 00000000..79325e21 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// osrusbfx2umsoftware.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/stdafx.h b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/stdafx.h new file mode 100644 index 00000000..edb61924 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/stdafx.h @@ -0,0 +1,18 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include <stdio.h> +#include <stdlib.h> +#include <tchar.h> +#include <Windows.h> +#include <initguid.h> +#include <Devpkey.h> +#include <SetupAPI.h> +#include <strsafe.h> +#include <cfgmgr32.h> + +// TODO: reference additional headers your program requires here diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/targetver.h b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_componentsoftware/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include <SDKDDKVer.h> diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension.sln b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension.sln new file mode 100644 index 00000000..6cc1d6b0 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension.sln @@ -0,0 +1,102 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "osrfx2_DCHU_extension", "osrfx2_DCHU_extension", "{4577857A-CCAE-42EB-BDE2-16C1E3DC7B14}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrfx2_DCHU_extension", "osrfx2_DCHU_extension\osrfx2_DCHU_extension.vcxproj", "{0588DF70-3923-42E6-8DC9-13C2C0186F20}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "osrfx2_DCHU_component", "osrfx2_DCHU_component", "{E148C50E-31A6-423E-A867-526FD51DA164}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrfx2_DCHU_component", "osrfx2_DCHU_component\osrfx2_DCHU_component.vcxproj", "{F90EFA96-B075-4531-B4E1-F406362D16BF}" + ProjectSection(ProjectDependencies) = postProject + {26D91630-B8FF-4102-A258-32F7D1C84E20} = {26D91630-B8FF-4102-A258-32F7D1C84E20} + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "osrfx2_DCHU_componentsoftware", "osrfx2_DCHU_componentsoftware", "{272BE7AA-9011-46FA-96C9-2051C9526476}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrfx2_DCHU_componentsoftware", "osrfx2_DCHU_componentsoftware\osrfx2_DCHU_componentsoftware.vcxproj", "{26D91630-B8FF-4102-A258-32F7D1C84E20}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|ARM = Release|ARM + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM.ActiveCfg = Debug|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM.Build.0 = Debug|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM.Deploy.0 = Debug|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM64.Build.0 = Debug|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x64.ActiveCfg = Debug|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x64.Build.0 = Debug|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x64.Deploy.0 = Debug|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x86.ActiveCfg = Debug|Win32 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x86.Build.0 = Debug|Win32 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x86.Deploy.0 = Debug|Win32 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM.ActiveCfg = Release|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM.Build.0 = Release|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM.Deploy.0 = Release|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM64.ActiveCfg = Release|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM64.Build.0 = Release|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM64.Deploy.0 = Release|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x64.ActiveCfg = Release|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x64.Build.0 = Release|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x64.Deploy.0 = Release|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x86.ActiveCfg = Release|Win32 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x86.Build.0 = Release|Win32 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x86.Deploy.0 = Release|Win32 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|ARM.ActiveCfg = Debug|ARM + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|ARM.Build.0 = Debug|ARM + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|ARM.Deploy.0 = Debug|ARM + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|ARM64.Build.0 = Debug|ARM64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|x64.ActiveCfg = Debug|x64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|x64.Build.0 = Debug|x64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|x64.Deploy.0 = Debug|x64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|x86.ActiveCfg = Debug|Win32 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|x86.Build.0 = Debug|Win32 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Debug|x86.Deploy.0 = Debug|Win32 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|ARM.ActiveCfg = Release|ARM + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|ARM.Build.0 = Release|ARM + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|ARM.Deploy.0 = Release|ARM + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|ARM64.ActiveCfg = Release|ARM64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|ARM64.Build.0 = Release|ARM64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|ARM64.Deploy.0 = Release|ARM64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|x64.ActiveCfg = Release|x64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|x64.Build.0 = Release|x64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|x64.Deploy.0 = Release|x64 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|x86.ActiveCfg = Release|Win32 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|x86.Build.0 = Release|Win32 + {F90EFA96-B075-4531-B4E1-F406362D16BF}.Release|x86.Deploy.0 = Release|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|ARM.ActiveCfg = Debug|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|ARM64.ActiveCfg = Debug|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|x64.ActiveCfg = Debug|x64 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|x64.Build.0 = Debug|x64 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|x86.ActiveCfg = Debug|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|x86.Build.0 = Debug|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|ARM.ActiveCfg = Release|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|ARM64.ActiveCfg = Release|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|x64.ActiveCfg = Release|x64 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|x64.Build.0 = Release|x64 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|x86.ActiveCfg = Release|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {0588DF70-3923-42E6-8DC9-13C2C0186F20} = {4577857A-CCAE-42EB-BDE2-16C1E3DC7B14} + {F90EFA96-B075-4531-B4E1-F406362D16BF} = {E148C50E-31A6-423E-A867-526FD51DA164} + {26D91630-B8FF-4102-A258-32F7D1C84E20} = {272BE7AA-9011-46FA-96C9-2051C9526476} + EndGlobalSection +EndGlobal diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.filters b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.filters new file mode 100644 index 00000000..0ba1a59c --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.filters @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Driver Files"> + <UniqueIdentifier>{8E41214B-6785-4CFE-B992-037D68949A14}</UniqueIdentifier> + <Extensions>inf;inv;inx;mof;mc;</Extensions> + </Filter> + </ItemGroup> + <ItemGroup> + <Inf Include="osrfx2_DCHU_extension.inx"> + <Filter>Driver Files</Filter> + </Inf> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx new file mode 100644 index 00000000..702a176c --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx @@ -0,0 +1,54 @@ +;/*++ +; +;Copyright (c) Microsoft Corporation. All rights reserved. +; +; THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY +; KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +; IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR +; PURPOSE. +; +;Module Name: +; +; osrfx2_DCHU_extension.INF +; +;Abstract: +; +; Extension inf for the OSR FX2 Learning Kit +; +;--*/ + +[Version] +Signature = "$WINDOWS NT$" +Class = Extension +ClassGuid = {e2f84ce7-8efa-411c-aa69-97454ca4cb57} +Provider = %ManufacturerName% +ExtensionId = {zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz} ; replace with your own GUID +CatalogFile = osrfx2_DCHU_extension.cat +DriverVer = 05/16/2017,15.14.36.721 + +[Manufacturer] +%ManufacturerName% = OsrFx2Extension, NT$ARCH$ + +[OsrFx2Extension.NT$ARCH$] +%OsrFx2.ExtensionDesc% = OsrFx2Extension_Install, USB\Vid_045e&Pid_94aa&mi_00 +%OsrFx2.ExtensionDesc% = OsrFx2Extension_Install, USB\Vid_0547&PID_1002 + +[OsrFx2Extension_Install.NT] +; Empty + +[OsrFx2Extension_Install.NT.HW] +AddReg = OsrFx2Extension_AddReg + +[OsrFx2Extension_AddReg] +HKR, OSR, "OperatingParams",, "-Extended" +HKR, OSR, "OperatingExceptions",, "x86" + +[OsrFx2Extension_Install.NT.Components] +AddComponent = osrfx2_DCHU_component,,OsrFx2Extension_ComponentInstall + +[OsrFx2Extension_ComponentInstall] +ComponentIds=VID_045e&PID_94ab + +[Strings] +ManufacturerName = "Contoso" +OsrFx2.ExtensionDesc = "OsrFx2 DCHU Device Extension" diff --git a/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.vcxproj b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.vcxproj new file mode 100644 index 00000000..bfc7ded6 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_loose/osrfx2_DCHU_extension/osrfx2_DCHU_extension.vcxproj @@ -0,0 +1,266 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|ARM"> + <Configuration>Debug</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM"> + <Configuration>Release</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|ARM64"> + <Configuration>Debug</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM64"> + <Configuration>Release</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + </ItemGroup> + <ItemGroup> + <Inf Include="osrfx2_DCHU_extension.inx" /> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{0588DF70-3923-42E6-8DC9-13C2C0186F20}</ProjectGuid> + <TemplateGuid>{4605da2c-74a5-4865-98e1-152ef136825f}</TemplateGuid> + <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion> + <MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion> + <Configuration>Debug</Configuration> + <Platform Condition="'$(Platform)' == ''">Win32</Platform> + <RootNamespace>osrfx2_DCHU_extension</RootNamespace> + <ProjectName>osrfx2_DCHU_extension</ProjectName> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_component/osrfx2_DCHU_component.inx b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_component/osrfx2_DCHU_component.inx new file mode 100644 index 00000000..8baab1a0 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_component/osrfx2_DCHU_component.inx @@ -0,0 +1,64 @@ +;/*++ +; +;Copyright (c) Microsoft Corporation. All rights reserved. +; +; THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY +; KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +; IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR +; PURPOSE. +; +;Module Name: +; +; osrfx2_DCHU_component.INF +; +;Abstract: +; +; Installation inf for one of the OSR FX2 Learning Kit's +; AddComponent directives +; +;--*/ + +[Version] +Signature = "$Windows NT$" +Class = SoftwareComponent +ClassGuid = {5c4c3332-344d-483c-8739-259e934c9cc8} +Provider = %ManufacturerName% +CatalogFile = osrfx2_DCHU_component.cat + +[Manufacturer] +%ManufacturerName% = OsrFx2Component, NT$ARCH$ + +[OsrFx2Component.NT$ARCH$] +%DeviceName% = OsrFx2Component_Install, SWC\VID_045e&PID_94ab + +[SourceDisksFiles] +osrfx2_DCHU_componentsoftware.exe = 1 + +[SourceDisksNames] +1 = %DiskName% + +[DestinationDirs] +OsrFx2Component_CopyFiles = 13 ; copy to driverstore + +[OsrFx2Component_Install.NT] +CopyFiles = OsrFx2Component_CopyFiles + +[OsrFx2Component_Install.NT.Services] +AddService = , 0x00000002 + +[OsrFx2Component_Install.NT.Software] +AddSoftware = osrfx2_DCHU_componentsoftware,, OsrFx2Component_SoftwareInstall + +[OsrFx2Component_SoftwareInstall] +SoftwareType = 1 +SoftwareBinary = osrfx2_DCHU_componentsoftware.exe +SoftwareArguments = <<DeviceInstanceId>> +SoftwareVersion = 1.0.0.0 + +[OsrFx2Component_CopyFiles] +osrfx2_DCHU_componentsoftware.exe + +[Strings] +ManufacturerName = "Contoso" +DiskName = "OsrFx2 DCHU Component Installation Disk" +DeviceName = "OsrFx2 DCHU Component Device"
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.cpp b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.cpp new file mode 100644 index 00000000..c14e66d1 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.cpp @@ -0,0 +1,489 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + osrfx2_DCHU_componentsoftware.cpp + +Abstract: + + An example .exe to run using the AddSoftware directive within an INF. + Contains an example on how to obtain a handle to the primary device using + SoftwareArguments within an AddSoftware directive's section. + +Environment: + + User mode + +--*/ + +#include "stdafx.h" + +#define BUFFER_SIZE (128 * sizeof(WCHAR)) +#define DEVICE_REG_SUBKEY L"OSR" +#define DEVICE_VALUE_OP_MODE L"OperatingMode" +#define DEVICE_VALUE_OP_PARAMS L"OperatingParams" +#define DEVICE_VALUE_OP_EXCEPTIONS L"OperatingExceptions" +#define CONTOSO_FILEPATH L"C:\\Program Files\\Contoso" +#define OSRFX2_DCHU_FILEPATH L"C:\\Program Files\\Contoso\\OsrFx2_DCHU" +#define FILEPATH L"C:\\Program Files\\Contoso\\OsrFx2_DCHU\\AddSoftwareInstallationFile.txt" +#define FILE_CONTENT L"Operating Mode: %ws\r\nOperating Params: %ws\r\nOperating Exceptions: %ws" + + +/*++ + +Routine Description: + +Arguments: + +Return Value: + + +--*/ +DWORD +WriteToFile( + _In_ PWSTR MessageText, + _In_ DWORD MessageTextLength + ) +{ + DWORD Err = ERROR_SUCCESS; + BOOL ErrorFlag = FALSE; + HANDLE hFile = INVALID_HANDLE_VALUE; + DWORD BytesToWrite; + DWORD BytesWritten; + + if (!CreateDirectory(CONTOSO_FILEPATH, NULL)) + { + Err = GetLastError(); + + if (Err == ERROR_ALREADY_EXISTS) + { + Err = ERROR_SUCCESS; + } + else + { + goto cleanup; + } + } + + if (!CreateDirectory(OSRFX2_DCHU_FILEPATH, NULL)) + { + Err = GetLastError(); + + if (Err == ERROR_ALREADY_EXISTS) + { + Err = ERROR_SUCCESS; + } + else + { + goto cleanup; + } + } + + hFile = CreateFile(FILEPATH, + GENERIC_WRITE, + 0, + NULL, + OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); + + if (hFile == INVALID_HANDLE_VALUE) + { + Err = ERROR_INVALID_PARAMETER; + goto cleanup; + } + + BytesToWrite = MessageTextLength * sizeof(WCHAR); + + ErrorFlag = WriteFile(hFile, + MessageText, + BytesToWrite, + &BytesWritten, + NULL); + + if ((!ErrorFlag) || + (BytesToWrite != BytesWritten)) + { + Err = GetLastError(); + goto cleanup; + } + +cleanup: + + if (hFile != INVALID_HANDLE_VALUE) + { + CloseHandle(hFile); + } + + return Err; +} + + +/*++ + +Routine Description: + + Obtains the handle to the device that used a separate Software Component + INF to install software. + +Arguments: + + Argc - The number of command line arguments + + Argv - The array of command line arguments + +Return Value: + + VOID + +--*/ +VOID +__cdecl +_tmain( + INT Argc, + TCHAR *Argv[]) +{ + DWORD Err = ERROR_SUCCESS; + HRESULT hr = S_OK; + BOOL ErrorFlag = FALSE; + DWORD BytesToWrite = 0; + DWORD BytesWritten = 0; + PTSTR DeviceInstanceId; + HDEVINFO DevInfoList = INVALID_HANDLE_VALUE; + SP_DEVINFO_DATA DevInfoData; + WCHAR ParentDeviceInstanceId[MAX_DEVICE_ID_LEN]; + DWORD RequiredSize; + DEVPROPTYPE DevPropType; + SP_DEVINFO_DATA ParentDevInfoData; + HKEY DevRegKey = NULL; + PWSTR OperatingMode = NULL; + PWSTR OperatingParams = NULL; + PWSTR OperatingExceptions = NULL; + DWORD ValueType; + DWORD ValueSize = BUFFER_SIZE; + HKEY DevOsrRegKey = NULL; + PWSTR FileText = NULL; + DWORD FileTextLength; + + // + // Validate arguments. + // + if (Argc != 2) + { + Err = ERROR_INVALID_PARAMETER; + goto cleanup; + } + + OperatingMode = (PWSTR)malloc(BUFFER_SIZE * sizeof(WCHAR)); + + if (OperatingMode == NULL) + { + Err = ERROR_OUTOFMEMORY; + goto cleanup; + } + + OperatingParams = (PWSTR)malloc(BUFFER_SIZE * sizeof(WCHAR)); + + if (OperatingParams == NULL) + { + Err = ERROR_OUTOFMEMORY; + goto cleanup; + } + + OperatingExceptions = (PWSTR)malloc(BUFFER_SIZE * sizeof(WCHAR)); + + if (OperatingExceptions == NULL) + { + Err = ERROR_OUTOFMEMORY; + goto cleanup; + } + + // + // Argv[1] should be the device instance ID. + // + DeviceInstanceId = Argv[1]; + + // + // Create a device info list to store queried device handles. + // + DevInfoList = SetupDiCreateDeviceInfoList(NULL, NULL); + + if (DevInfoList == INVALID_HANDLE_VALUE) + { + Err = ERROR_OUTOFMEMORY; + goto cleanup; + } + + DevInfoData.cbSize = sizeof(SP_DEVINFO_DATA); + + // + // Add the Software Component device that called AddSoftware to the + // device info list, which will be used to find the primary device that + // called AddComponent in the first place. + // + if (!SetupDiOpenDeviceInfo(DevInfoList, + DeviceInstanceId, + NULL, + 0, + &DevInfoData)) + { + Err = GetLastError(); + goto cleanup; + } + + // + // Get the device instance id of the opened device's parent. + // + if (!SetupDiGetDeviceProperty(DevInfoList, + &DevInfoData, + &DEVPKEY_Device_Parent, + &DevPropType, + (PBYTE)ParentDeviceInstanceId, + sizeof(ParentDeviceInstanceId), + &RequiredSize, + 0)) + { + Err = GetLastError(); + goto cleanup; + } + + if ((DevPropType != DEVPROP_TYPE_STRING) || + (RequiredSize < sizeof(WCHAR))) + { + Err = ERROR_INVALID_PARAMETER; + goto cleanup; + } + + ParentDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA); + + // + // Get the parent of the device we retrieved first, which is the device + // that called AddComponent in its INF. + // + if (!SetupDiOpenDeviceInfoW(DevInfoList, + ParentDeviceInstanceId, + NULL, + 0, + &ParentDevInfoData)) + { + Err = GetLastError(); + goto cleanup; + } + + // + // Open up the HW registry keys of the primary device. + // + DevRegKey = SetupDiOpenDevRegKey(DevInfoList, + &ParentDevInfoData, + DICS_FLAG_GLOBAL, + 0, + DIREG_DEV, + KEY_READ); + + if (DevRegKey == INVALID_HANDLE_VALUE) + { + Err = GetLastError(); + DevRegKey = NULL; + goto cleanup; + } + + Err = RegOpenKeyEx(DevRegKey, + DEVICE_REG_SUBKEY, + 0, + KEY_QUERY_VALUE, + &DevOsrRegKey); + + if (Err != ERROR_SUCCESS) + { + goto cleanup; + } + + // + // Retrieve the registry values defined in the primary device's INF. + // Note that if the extension INF was applied, the extension INF would + // overwrite OperatingParams and create OperatingExceptions. + // + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_MODE, + NULL, + &ValueType, + (LPBYTE)OperatingMode, + &ValueSize); + + while (Err == ERROR_MORE_DATA) + { + // + // Create a larger buffer. + // + OperatingMode = (PTSTR)realloc(OperatingMode, ValueSize); + + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_MODE, + NULL, + &ValueType, + (LPBYTE)OperatingMode, + &ValueSize); + } + + if (Err != ERROR_SUCCESS) + { + OperatingMode[0] = TEXT('\0'); + } + else if ((ValueType != REG_SZ) || + (ValueSize < sizeof(TCHAR))) + { + Err = ERROR_REGISTRY_CORRUPT; + OperatingMode[0] = TEXT('\0'); + } + + ValueSize = BUFFER_SIZE; + + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_PARAMS, + NULL, + &ValueType, + (LPBYTE)OperatingParams, + &ValueSize); + + while (Err == ERROR_MORE_DATA) + { + // + // Create a larger buffer. + // + OperatingParams = (PTSTR)realloc(OperatingParams, ValueSize); + + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_MODE, + NULL, + &ValueType, + (LPBYTE)OperatingParams, + &ValueSize); + } + + if (Err != ERROR_SUCCESS) + { + OperatingParams[0] = TEXT('\0'); + } + else if ((ValueType != REG_SZ) || + (ValueSize < sizeof(TCHAR))) + { + Err = ERROR_REGISTRY_CORRUPT; + OperatingParams[0] = TEXT('\0'); + } + + ValueSize = BUFFER_SIZE; + + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_EXCEPTIONS, + NULL, + &ValueType, + (LPBYTE)OperatingExceptions, + &ValueSize); + + while (Err == ERROR_MORE_DATA) + { + // + // Create a larger buffer. + // + OperatingExceptions = (PTSTR)realloc(OperatingExceptions, ValueSize); + + Err = RegQueryValueEx(DevOsrRegKey, + DEVICE_VALUE_OP_EXCEPTIONS, + NULL, + &ValueType, + (LPBYTE)OperatingExceptions, + &ValueSize); + } + + if (Err != ERROR_SUCCESS) + { + OperatingExceptions[0] = TEXT('\0'); + } + else if ((ValueType != REG_SZ) || + (ValueSize < sizeof(TCHAR))) + { + Err = ERROR_REGISTRY_CORRUPT; + OperatingExceptions[0] = TEXT('\0'); + } + + FileTextLength = (DWORD)wcslen(OperatingMode) + + (DWORD)wcslen(OperatingParams) + + (DWORD)wcslen(OperatingExceptions) + + (DWORD)wcslen(FILE_CONTENT) - + 9; // Subtract the 3 %ws + + FileText = (PWSTR)malloc((FileTextLength + 1) * sizeof(WCHAR)); + + if (FileText == NULL) + { + Err = ERROR_OUTOFMEMORY; + goto cleanup; + } + + hr = StringCchPrintf(FileText, + FileTextLength + 1, + FILE_CONTENT, + OperatingMode, + OperatingParams, + OperatingExceptions); + + if (FAILED(hr)) + { + Err = HRESULT_CODE(hr); + goto cleanup; + } + + Err = WriteToFile(FileText, FileTextLength); + + if (Err != ERROR_SUCCESS) + { + goto cleanup; + } + +cleanup: + + if (FileText != NULL) + { + free(FileText); + } + + if (OperatingExceptions != NULL) + { + free(OperatingExceptions); + } + + if (OperatingParams != NULL) + { + free(OperatingParams); + } + + if (OperatingMode != NULL) + { + free(OperatingMode); + } + + if (DevOsrRegKey != NULL) + { + RegCloseKey(DevOsrRegKey); + } + + if (DevRegKey != NULL) + { + RegCloseKey(DevRegKey); + } + + if (DevInfoList != INVALID_HANDLE_VALUE) + { + SetupDiDestroyDeviceInfoList(DevInfoList); + } + + return; +} + diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.filters b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.filters new file mode 100644 index 00000000..395438fa --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.filters @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Source Files"> + <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> + <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> + </Filter> + <Filter Include="Header Files"> + <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> + <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions> + </Filter> + <Filter Include="Resource Files"> + <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> + <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> + </Filter> + </ItemGroup> + <ItemGroup> + <Text Include="ReadMe.txt" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="stdafx.h"> + <Filter>Header Files</Filter> + </ClInclude> + </ItemGroup> + <ItemGroup> + <ClCompile Include="stdafx.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="osrfx2_DCHU_componentsoftware.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.vcxproj b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.vcxproj new file mode 100644 index 00000000..931646bb --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/osrfx2_DCHU_componentsoftware.vcxproj @@ -0,0 +1,169 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{26D91630-B8FF-4102-A258-32F7D1C84E20}</ProjectGuid> + <Keyword>Win32Proj</Keyword> + <RootNamespace>osrfx2_DCHU_componentsoftware</RootNamespace> + <WindowsTargetPlatformVersion>10.0.15063.0</WindowsTargetPlatformVersion> + <ProjectName>osrfx2_DCHU_componentsoftware</ProjectName> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>v140</PlatformToolset> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>v140</PlatformToolset> + <WholeProgramOptimization>false</WholeProgramOptimization> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>v140</PlatformToolset> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>v140</PlatformToolset> + <WholeProgramOptimization>false</WholeProgramOptimization> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="Shared"> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <LinkIncremental>true</LinkIncremental> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <LinkIncremental>true</LinkIncremental> + <TargetName>$(ProjectName)</TargetName> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <LinkIncremental>false</LinkIncremental> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <LinkIncremental>false</LinkIncremental> + <TargetName>$(ProjectName)</TargetName> + <TargetExt>.exe</TargetExt> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <PrecompiledHeader>Use</PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <Optimization>Disabled</Optimization> + <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;setupapi.lib;</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <PrecompiledHeader>Use</PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <Optimization>Disabled</Optimization> + <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;setupapi.lib;</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <ClCompile> + <WarningLevel>Level3</WarningLevel> + <PrecompiledHeader>Use</PrecompiledHeader> + <Optimization>MaxSpeed</Optimization> + <FunctionLevelLinking>true</FunctionLevelLinking> + <IntrinsicFunctions>true</IntrinsicFunctions> + <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <EnableCOMDATFolding>true</EnableCOMDATFolding> + <OptimizeReferences>true</OptimizeReferences> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;setupapi.lib;</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <WarningLevel>Level3</WarningLevel> + <PrecompiledHeader>Use</PrecompiledHeader> + <Optimization>MaxSpeed</Optimization> + <FunctionLevelLinking>true</FunctionLevelLinking> + <IntrinsicFunctions>true</IntrinsicFunctions> + <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <EnableCOMDATFolding>true</EnableCOMDATFolding> + <OptimizeReferences>true</OptimizeReferences> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;setupapi.lib;</AdditionalDependencies> + </Link> + </ItemDefinitionGroup> + <ItemGroup> + <Text Include="ReadMe.txt" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="stdafx.h" /> + </ItemGroup> + <ItemGroup> + <ClCompile Include="osrfx2_DCHU_componentsoftware.cpp" /> + <ClCompile Include="stdafx.cpp"> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader> + </ClCompile> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/stdafx.cpp b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/stdafx.cpp new file mode 100644 index 00000000..79325e21 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// osrusbfx2umsoftware.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/stdafx.h b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/stdafx.h new file mode 100644 index 00000000..edb61924 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/stdafx.h @@ -0,0 +1,18 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include <stdio.h> +#include <stdlib.h> +#include <tchar.h> +#include <Windows.h> +#include <initguid.h> +#include <Devpkey.h> +#include <SetupAPI.h> +#include <strsafe.h> +#include <cfgmgr32.h> + +// TODO: reference additional headers your program requires here diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/targetver.h b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_componentsoftware/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include <SDKDDKVer.h> diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension.sln b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension.sln new file mode 100644 index 00000000..40b15034 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension.sln @@ -0,0 +1,73 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "osrfx2_DCHU_extension", "osrfx2_DCHU_extension", "{4577857A-CCAE-42EB-BDE2-16C1E3DC7B14}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrfx2_DCHU_extension", "osrfx2_DCHU_extension\osrfx2_DCHU_extension.vcxproj", "{0588DF70-3923-42E6-8DC9-13C2C0186F20}" + ProjectSection(ProjectDependencies) = postProject + {26D91630-B8FF-4102-A258-32F7D1C84E20} = {26D91630-B8FF-4102-A258-32F7D1C84E20} + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "osrfx2_DCHU_componentsoftware", "osrfx2_DCHU_componentsoftware", "{B327FC27-5816-4F28-959F-4C35F1D22678}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "osrfx2_DCHU_componentsoftware", "osrfx2_DCHU_componentsoftware\osrfx2_DCHU_componentsoftware.vcxproj", "{26D91630-B8FF-4102-A258-32F7D1C84E20}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|ARM = Release|ARM + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM.ActiveCfg = Debug|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM.Build.0 = Debug|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM.Deploy.0 = Debug|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM64.Build.0 = Debug|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x64.ActiveCfg = Debug|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x64.Build.0 = Debug|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x64.Deploy.0 = Debug|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x86.ActiveCfg = Debug|Win32 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x86.Build.0 = Debug|Win32 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Debug|x86.Deploy.0 = Debug|Win32 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM.ActiveCfg = Release|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM.Build.0 = Release|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM.Deploy.0 = Release|ARM + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM64.ActiveCfg = Release|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM64.Build.0 = Release|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|ARM64.Deploy.0 = Release|ARM64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x64.ActiveCfg = Release|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x64.Build.0 = Release|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x64.Deploy.0 = Release|x64 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x86.ActiveCfg = Release|Win32 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x86.Build.0 = Release|Win32 + {0588DF70-3923-42E6-8DC9-13C2C0186F20}.Release|x86.Deploy.0 = Release|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|ARM.ActiveCfg = Debug|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|ARM64.ActiveCfg = Debug|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|x64.ActiveCfg = Debug|x64 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|x64.Build.0 = Debug|x64 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|x86.ActiveCfg = Debug|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Debug|x86.Build.0 = Debug|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|ARM.ActiveCfg = Release|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|ARM64.ActiveCfg = Release|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|x64.ActiveCfg = Release|x64 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|x64.Build.0 = Release|x64 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|x86.ActiveCfg = Release|Win32 + {26D91630-B8FF-4102-A258-32F7D1C84E20}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {0588DF70-3923-42E6-8DC9-13C2C0186F20} = {4577857A-CCAE-42EB-BDE2-16C1E3DC7B14} + {26D91630-B8FF-4102-A258-32F7D1C84E20} = {B327FC27-5816-4F28-959F-4C35F1D22678} + EndGlobalSection +EndGlobal diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.filters b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.filters new file mode 100644 index 00000000..0ba1a59c --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.filters @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Driver Files"> + <UniqueIdentifier>{8E41214B-6785-4CFE-B992-037D68949A14}</UniqueIdentifier> + <Extensions>inf;inv;inx;mof;mc;</Extensions> + </Filter> + </ItemGroup> + <ItemGroup> + <Inf Include="osrfx2_DCHU_extension.inx"> + <Filter>Driver Files</Filter> + </Inf> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx new file mode 100644 index 00000000..570cd389 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.inx @@ -0,0 +1,55 @@ +;/*++ +; +;Copyright (c) Microsoft Corporation. All rights reserved. +; +; THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY +; KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +; IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR +; PURPOSE. +; +;Module Name: +; +; osrfx2_DCHU_extension.INF +; +;Abstract: +; +; Extension inf for the OSR FX2 Learning Kit +; +;--*/ + +[Version] +Signature = "$WINDOWS NT$" +Class = Extension +ClassGuid = {e2f84ce7-8efa-411c-aa69-97454ca4cb57} +Provider = %ManufacturerName% +ExtensionId = {zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz} ; replace with your own GUID +CatalogFile = osrfx2_DCHU_extension.cat +DriverVer = 05/16/2017,15.14.36.721 + +[Manufacturer] +%ManufacturerName% = OsrFx2Extension, NT$ARCH$ + +[OsrFx2Extension.NT$ARCH$] +%OsrFx2.ExtensionDesc% = OsrFx2Extension_Install, USB\Vid_045e&Pid_94aa&mi_00 +%OsrFx2.ExtensionDesc% = OsrFx2Extension_Install, USB\Vid_0547&PID_1002 + +[OsrFx2Extension_Install.NT] +CopyInf=osrfx2_DCHU_component.inf + +[OsrFx2Extension_Install.NT.HW] +AddReg = OsrFx2Extension_AddReg +AddReg = OsrFx2Extension_COMAddReg + +[OsrFx2Extension_AddReg] +HKR, OSR, "OperatingParams",, "-Extended" +HKR, OSR, "OperatingExceptions",, "x86" + +[OsrFx2Extension_Install.NT.Components] +AddComponent = osrfx2_DCHU_component,,OsrFx2Extension_ComponentInstall + +[OsrFx2Extension_ComponentInstall] +ComponentIds=VID_045e&PID_94ab + +[Strings] +ManufacturerName = "Contoso" +OsrFx2.ExtensionDesc = "OsrFx2 DCHU Device Extension" diff --git a/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.vcxproj b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.vcxproj new file mode 100644 index 00000000..4542c3a7 --- /dev/null +++ b/general/DCHU/osrfx2_DCHU_extension_tight/osrfx2_DCHU_extension/osrfx2_DCHU_extension.vcxproj @@ -0,0 +1,273 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|ARM"> + <Configuration>Debug</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM"> + <Configuration>Release</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|ARM64"> + <Configuration>Debug</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM64"> + <Configuration>Release</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + </ItemGroup> + <ItemGroup> + <Inf Include="..\osrfx2_DCHU_component\osrfx2_DCHU_component.inx" /> + <Inf Include="osrfx2_DCHU_extension.inx" /> + </ItemGroup> + <ItemGroup> + <FilesToPackage Include="C:\Users\mamont\Documents\GitHub\Windows-driver-samples\general\DCHU\osrfx2_DCHU_extension_tight\x64\Release\osrfx2_DCHU_componentsoftware.exe"> + <PackageRelativeDirectory> + </PackageRelativeDirectory> + </FilesToPackage> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{0588DF70-3923-42E6-8DC9-13C2C0186F20}</ProjectGuid> + <TemplateGuid>{4605da2c-74a5-4865-98e1-152ef136825f}</TemplateGuid> + <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion> + <MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion> + <Configuration>Debug</Configuration> + <Platform Condition="'$(Platform)' == ''">Win32</Platform> + <RootNamespace>osrfx2_DCHU_extension</RootNamespace> + <ProjectName>osrfx2_DCHU_extension</ProjectName> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Utility</ConfigurationType> + <DriverType>Package</DriverType> + <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <DebuggerFlavor>DbgengRemoteDebugger</DebuggerFlavor> + <HardwareIdString /> + <CommandLine /> + <DeployFiles /> + <EnableVerifier>False</EnableVerifier> + <AllDrivers>False</AllDrivers> + <VerifyProjectOutput>True</VerifyProjectOutput> + <VerifyDrivers /> + <VerifyFlags>133563</VerifyFlags> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Inf> + <Architecture>$(InfArch)</Architecture> + <TimeStamp>1.0.0.0</TimeStamp> + </Inf> + </ItemDefinitionGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/general/PLX9x5x/README.md b/general/PLX9x5x/README.md index a706b7d0..e665839b 100644 --- a/general/PLX9x5x/README.md +++ b/general/PLX9x5x/README.md @@ -1,3 +1,13 @@ +<!--- + name: PLX9x5x PCI Driver + platform: KMDF + language: cpp + category: General PCI WDF + description: Demonstrates how to write a driver for a generic PCI device using Windows Driver Frameworks (WDF). + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617719 +---> + + PLX9x5x PCI Driver ================== diff --git a/general/PLX9x5x/sys/Pci9x5x.vcxproj b/general/PLX9x5x/sys/Pci9x5x.vcxproj index c422c342..c46f37d4 100644 --- a/general/PLX9x5x/sys/Pci9x5x.vcxproj +++ b/general/PLX9x5x/sys/Pci9x5x.vcxproj @@ -210,7 +210,7 @@ <ResourceCompile Include="Pci9656.rc" /> </ItemGroup> <ItemGroup> - <Inf Exclude="@(Inf)" Include="*.inf" /> + <Inf Exclude="@(Inf)" Include="*.inx" /> <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'" /> </ItemGroup> <ItemGroup> diff --git a/general/SystemDma/wdm/README.md b/general/SystemDma/wdm/README.md index a077fe8d..ad7d9dbc 100644 --- a/general/SystemDma/wdm/README.md +++ b/general/SystemDma/wdm/README.md @@ -1,3 +1,13 @@ +<!--- + name: System DMA sample + platform: WDM + language: cpp + category: General + description: Demonstrates how a driver could use a system DMA controller to write data to a hardware location using V3 System DMA. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617722 +---> + + System DMA ========== diff --git a/general/WinHEC 2017 Lab/PlugInToaster/devcon.exe b/general/WinHEC 2017 Lab/PlugInToaster/devcon.exe Binary files differnew file mode 100644 index 00000000..92f91505 --- /dev/null +++ b/general/WinHEC 2017 Lab/PlugInToaster/devcon.exe diff --git a/general/WinHEC 2017 Lab/PlugInToaster/plug.exe b/general/WinHEC 2017 Lab/PlugInToaster/plug.exe Binary files differnew file mode 100644 index 00000000..d84aa38b --- /dev/null +++ b/general/WinHEC 2017 Lab/PlugInToaster/plug.exe diff --git a/general/WinHEC 2017 Lab/PlugInToaster/unplug.bat b/general/WinHEC 2017 Lab/PlugInToaster/unplug.bat new file mode 100644 index 00000000..324ae1cf --- /dev/null +++ b/general/WinHEC 2017 Lab/PlugInToaster/unplug.bat @@ -0,0 +1,2 @@ +@sc delete hsa_usersrv +@devcon remove TOASTER\BASIC_TOASTER
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/HsaService.cpp b/general/WinHEC 2017 Lab/Toaster Driver/Service/HsaService.cpp new file mode 100644 index 00000000..d3f70fdf --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/HsaService.cpp @@ -0,0 +1,116 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "stdafx.h" + +#pragma region Includes +#include <stdio.h> +#include <windows.h> +#include "ServiceInstaller.h" +#include "ServiceBase.h" +#include "SampleService.h" +#pragma endregion + +// +// Settings of the service +// + +// Internal name of the service +#define SERVICE_NAME L"HsaService" + +// Displayed name of the service +#define SERVICE_DISPLAY_NAME L"Hsa Sample Service" + +// Service start options. +#define SERVICE_START_TYPE SERVICE_DEMAND_START + +// List of service dependencies - "dep1\0dep2\0\0" +#define SERVICE_DEPENDENCIES L"" + +// The name of the account under which the service should run - NULL uses LocalSystem account. +#define SERVICE_ACCOUNT NULL + +// The password to the service account name +#define SERVICE_PASSWORD NULL + + +// +// FUNCTION: wmain(int, wchar_t *[]) +// +// PURPOSE: entrypoint for the application. +// +// PARAMETERS: +// argc - number of command line arguments +// argv - array of command line arguments +// +// RETURN VALUE: +// none +// +// COMMENTS: +// wmain() either performs the command line task, or run the service. +// +int wmain(_In_ int argc, _In_ wchar_t *argv[]) +{ + bool invalidArgs = false; + + if ((argc > 1) && ((*argv[1] == L'-' || (*argv[1] == L'/')))) + { + if (_wcsicmp(L"install", argv[1] + 1) == 0) + { + // Install the service when the command is + // "-install" or "/install". + InstallService( + SERVICE_NAME, // Name of service + SERVICE_DISPLAY_NAME, // Name to display + SERVICE_START_TYPE, // Service start type + SERVICE_DEPENDENCIES, // Dependencies + SERVICE_ACCOUNT, // Service running account + SERVICE_PASSWORD // Password of the account + ); + } + else if (_wcsicmp(L"remove", argv[1] + 1) == 0) + { + // Uninstall the service when the command is + // "-remove" or "/remove". + UninstallService(SERVICE_NAME); + } + else if (_wcsicmp(L"console", argv[1] + 1) == 0) + { + // Uninstall the service when the command is + // "-remove" or "/remove". + CSampleService service(SERVICE_NAME); + service.ConsoleRun(); + } + else + { + invalidArgs = true; + } + } + else + { + invalidArgs = true; + CSampleService service(SERVICE_NAME); + if (!CServiceBase::Run(service)) + { + wprintf(L"Service failed to run w/err 0x%08lx\n", GetLastError()); + } + } + + if (invalidArgs) + { + wprintf(L"Parameters:\n"); + wprintf(L" -install to install the service.\n"); + wprintf(L" -remove to remove the service.\n"); + wprintf(L" -console to run in console mode.\n"); + } + + return 0; +}
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/Metering.cpp b/general/WinHEC 2017 Lab/Toaster Driver/Service/Metering.cpp new file mode 100644 index 00000000..1766b37c --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/Metering.cpp @@ -0,0 +1,148 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "stdafx.h" +#include "Metering.h" +#include <assert.h> +#include "RpcInterface_h.h" + +using namespace RpcServer; + +// +// Thread pool callback method for metering worker +// +void CALLBACK MeteringWorkerTpCallback( + _In_ PTP_CALLBACK_INSTANCE /*iTimerInstance*/, + _In_ PVOID pContext, + _In_ PTP_TIMER /*pTimer*/) +{ + Metering *metering = static_cast<Metering *>(pContext); + + if (metering != nullptr) + { + // Run the metering worker for this instance of metering + metering->MeteringWorker(); + } +} + +// +// ctor for Metering +// +Metering::Metering( + _In_ __int64 period) +{ + tpTimer = CreateThreadpoolTimer(::MeteringWorkerTpCallback, this, nullptr); + // TODO: Handle if CreateThreadpoolTimer fails i.e tpTimer == nullptr + + samplePeriod = period; + event = CreateEvent( + nullptr, // default security attributes + FALSE, // auto-reset event object + FALSE, // initial state is nonsignaled + nullptr); // unnamed object +} + +// +// dtor for Metering +// +Metering::~Metering() +{ + if (tpTimer != nullptr) + { + // How to close threadpool timer when there are outstanding callbacks: + // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682040(v=vs.85).aspx + SetThreadpoolTimer(tpTimer, nullptr, 0, 0); + WaitForThreadpoolTimerCallbacks(tpTimer, true); + CloseThreadpoolTimer(tpTimer); + tpTimer = nullptr; + } + CloseHandle(event); +} + +// +// Set the lowest sample period +// +void Metering::SetSamplePeriod(_In_ __int64 period) +{ + if (period < 1) + { + // Don't allow 0 (too fast) or negative numbers. + period = 1; + } + if (period > 1000) + { + // Don't let the period be too long, or we will be + // slow to shut down. + period = 1000; + } + samplePeriod = period; +} + +// +// Get last known metering data +// +__int64 Metering::GetMeteringData() const +{ + return _data; +} + +// +// Metering worker that updates metering data +// +void Metering::MeteringWorker() +{ + // Get the value from the imaginary driver and update the data + _data = GetTickCount(); + SetEvent(event); +} + +// +// Set the thread poot timer and wait for metering data. +// +void Metering::WaitForMeteringData() const +{ + ULARGE_INTEGER ulDueTime; + FILETIME FileDueTime; + ulDueTime.QuadPart = static_cast<ULONGLONG>(-(1 * 10 * 1000 * samplePeriod)); + FileDueTime.dwHighDateTime = ulDueTime.HighPart; + FileDueTime.dwLowDateTime = ulDueTime.LowPart; + + SetThreadpoolTimer(tpTimer, + &FileDueTime, + 0, + 0); + + WaitForSingleObject(event, INFINITE); +} + +void Metering::StartMetering( + _In_ __int64 samplePeriod, + _In_ __int64 context) +{ + stopMeteringRequested = false; + SetSamplePeriod(samplePeriod); + + while (true) + { + WaitForMeteringData(); + if (stopMeteringRequested || ShutdownRequested) + { + break; + } + MeteringDataEvent(GetMeteringData(), context); + } +} + +void Metering::StopMetering() +{ + stopMeteringRequested = true; +} + diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/Metering.h b/general/WinHEC 2017 Lab/Toaster Driver/Service/Metering.h new file mode 100644 index 00000000..bfb48216 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/Metering.h @@ -0,0 +1,29 @@ +#include "stdafx.h" +#include <windows.h> + +#include <iostream> // std::cout +#include <thread> // std::thread +#include <mutex> + +namespace RpcServer +{ + class Metering + { + public: + Metering(__int64 period); + void SetSamplePeriod(__int64 period); + __int64 GetMeteringData() const; + void MeteringWorker(); + void WaitForMeteringData() const; + void StartMetering(__int64 samplePeriod, __int64 context); + void StopMetering(); + ~Metering(); + + private: + volatile __int64 _data; + volatile __int64 samplePeriod; + PTP_TIMER tpTimer = nullptr; + HANDLE event; + volatile bool stopMeteringRequested = false; + }; +} diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface.Idl b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface.Idl new file mode 100644 index 00000000..1b4b74cc --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface.Idl @@ -0,0 +1,51 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +import "oaidl.idl"; +import "unknwn.idl"; + +[uuid (906B0CE0-C70B-1067-B317-00DD010662DA), +version(1.0), +pointer_default(unique), +] +interface RpcInterface +{ + + // context_handle_noserialize in acf for RPC to call rundown when the client goes away + typedef [context_handle] void* PCONTEXT_HANDLE_TYPE; + typedef [ref] PCONTEXT_HANDLE_TYPE * PPCONTEXT_HANDLE_TYPE; + + // + // RPC methods to retrieve/clean client context + // + void RemoteOpen([in] handle_t hBinding, + [out] PPCONTEXT_HANDLE_TYPE pphContext); + + void RemoteClose([in, out] PPCONTEXT_HANDLE_TYPE pphContext); + + // + // Metering Interface + // + void StartMetering( + [in] PCONTEXT_HANDLE_TYPE phContext, + [in] __int64 samplePeriod, + [in, optional] __int64 context); + + void SetSamplePeriod( + [in] PCONTEXT_HANDLE_TYPE phContext, + [in] __int64 samplePeriod); + + void StopMetering([in] PCONTEXT_HANDLE_TYPE phContext); + + [callback] void MeteringDataEvent( + [in] __int64 data, + [in, optional] __int64 context); +} diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface.acf b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface.acf new file mode 100644 index 00000000..d00ed5af --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface.acf @@ -0,0 +1,17 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the Microsoft Public License. +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + + +interface RpcInterface +{ + // We need the RPC to call rundown when the client goes away + typedef [context_handle_noserialize] PCONTEXT_HANDLE_TYPE; +} diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface_c.c b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface_c.c new file mode 100644 index 00000000..fbe0a799 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface_c.c @@ -0,0 +1,476 @@ + + +/* this ALWAYS GENERATED file contains the RPC client stubs */ + + + /* File created by MIDL compiler version 8.01.0622 */ +/* at Mon Jan 18 19:14:07 2038 + */ +/* Compiler settings for RpcInterface.Idl: + Oicf, W1, Zp8, env=Win64 (32b run), target_arch=AMD64 8.01.0622 + protocol : dce , ms_ext, c_ext, robust + error checks: allocation ref bounds_check enum stub_data + VC __declspec() decoration level: + __declspec(uuid()), __declspec(selectany), __declspec(novtable) + DECLSPEC_UUID(), MIDL_INTERFACE() +*/ +/* @@MIDL_FILE_HEADING( ) */ + +#if defined(_M_AMD64) + + +#pragma warning( disable: 4049 ) /* more than 64k source lines */ +#if _MSC_VER >= 1200 +#pragma warning(push) +#endif + +#pragma warning( disable: 4211 ) /* redefine extern to static */ +#pragma warning( disable: 4232 ) /* dllimport identity*/ +#pragma warning( disable: 4024 ) /* array to pointer mapping*/ + +#include <string.h> + +#include "RpcInterface_h.h" + +#define TYPE_FORMAT_STRING_SIZE 23 +#define PROC_FORMAT_STRING_SIZE 245 +#define EXPR_FORMAT_STRING_SIZE 1 +#define TRANSMIT_AS_TABLE_SIZE 0 +#define WIRE_MARSHAL_TABLE_SIZE 0 + +typedef struct _RpcInterface_MIDL_TYPE_FORMAT_STRING + { + short Pad; + unsigned char Format[ TYPE_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_TYPE_FORMAT_STRING; + +typedef struct _RpcInterface_MIDL_PROC_FORMAT_STRING + { + short Pad; + unsigned char Format[ PROC_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_PROC_FORMAT_STRING; + +typedef struct _RpcInterface_MIDL_EXPR_FORMAT_STRING + { + long Pad; + unsigned char Format[ EXPR_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_EXPR_FORMAT_STRING; + + +static const RPC_SYNTAX_IDENTIFIER _RpcTransferSyntax = +{{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}}; + + +extern const RpcInterface_MIDL_TYPE_FORMAT_STRING RpcInterface__MIDL_TypeFormatString; +extern const RpcInterface_MIDL_PROC_FORMAT_STRING RpcInterface__MIDL_ProcFormatString; +extern const RpcInterface_MIDL_EXPR_FORMAT_STRING RpcInterface__MIDL_ExprFormatString; + +#define GENERIC_BINDING_TABLE_SIZE 0 + + +/* Standard interface: RpcInterface, ver. 1.0, + GUID={0x906B0CE0,0xC70B,0x1067,{0xB3,0x17,0x00,0xDD,0x01,0x06,0x62,0xDA}} */ + + +extern const MIDL_SERVER_INFO RpcInterface_ServerInfo; + + +extern const RPC_DISPATCH_TABLE RpcInterface_v1_0_DispatchTable; + +static const RPC_CLIENT_INTERFACE RpcInterface___RpcClientInterface = + { + sizeof(RPC_CLIENT_INTERFACE), + {{0x906B0CE0,0xC70B,0x1067,{0xB3,0x17,0x00,0xDD,0x01,0x06,0x62,0xDA}},{1,0}}, + {{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}}, + (RPC_DISPATCH_TABLE*)&RpcInterface_v1_0_DispatchTable, + 0, + 0, + 0, + &RpcInterface_ServerInfo, + 0x04000000 + }; +RPC_IF_HANDLE RpcInterface_v1_0_c_ifspec = (RPC_IF_HANDLE)& RpcInterface___RpcClientInterface; + +extern const MIDL_STUB_DESC RpcInterface_StubDesc; + +static RPC_BINDING_HANDLE RpcInterface__MIDL_AutoBindHandle; + + +void RemoteOpen( + /* [in] */ handle_t hBinding, + /* [out] */ PPCONTEXT_HANDLE_TYPE pphContext) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[0], + hBinding, + pphContext); + +} + + +void RemoteClose( + /* [out][in] */ PPCONTEXT_HANDLE_TYPE pphContext) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[36], + pphContext); + +} + + +void StartMetering( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext, + /* [in] */ __int64 samplePeriod, + /* [optional][in] */ __int64 context) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[74], + phContext, + samplePeriod, + context); + +} + + +void SetSamplePeriod( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext, + /* [in] */ __int64 samplePeriod) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[124], + phContext, + samplePeriod); + +} + + +void StopMetering( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[168], + phContext); + +} + + +#if !defined(__RPC_WIN64__) +#error Invalid build platform for this stub. +#endif + +static const RpcInterface_MIDL_PROC_FORMAT_STRING RpcInterface__MIDL_ProcFormatString = + { + 0, + { + + /* Procedure RemoteOpen */ + + 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 2 */ NdrFcLong( 0x0 ), /* 0 */ +/* 6 */ NdrFcShort( 0x0 ), /* 0 */ +/* 8 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 10 */ 0x32, /* FC_BIND_PRIMITIVE */ + 0x0, /* 0 */ +/* 12 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 14 */ NdrFcShort( 0x0 ), /* 0 */ +/* 16 */ NdrFcShort( 0x38 ), /* 56 */ +/* 18 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 20 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 22 */ NdrFcShort( 0x0 ), /* 0 */ +/* 24 */ NdrFcShort( 0x0 ), /* 0 */ +/* 26 */ NdrFcShort( 0x0 ), /* 0 */ +/* 28 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter pphContext */ + +/* 30 */ NdrFcShort( 0x110 ), /* Flags: out, simple ref, */ +/* 32 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 34 */ NdrFcShort( 0x6 ), /* Type Offset=6 */ + + /* Procedure RemoteClose */ + +/* 36 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 38 */ NdrFcLong( 0x0 ), /* 0 */ +/* 42 */ NdrFcShort( 0x1 ), /* 1 */ +/* 44 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 46 */ 0x30, /* FC_BIND_CONTEXT */ + 0xe4, /* Ctxt flags: via ptr, in, out, no serialize, */ +/* 48 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 50 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 52 */ NdrFcShort( 0x38 ), /* 56 */ +/* 54 */ NdrFcShort( 0x38 ), /* 56 */ +/* 56 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 58 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 60 */ NdrFcShort( 0x0 ), /* 0 */ +/* 62 */ NdrFcShort( 0x0 ), /* 0 */ +/* 64 */ NdrFcShort( 0x0 ), /* 0 */ +/* 66 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter pphContext */ + +/* 68 */ NdrFcShort( 0x118 ), /* Flags: in, out, simple ref, */ +/* 70 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 72 */ NdrFcShort( 0xe ), /* Type Offset=14 */ + + /* Procedure StartMetering */ + +/* 74 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 76 */ NdrFcLong( 0x0 ), /* 0 */ +/* 80 */ NdrFcShort( 0x2 ), /* 2 */ +/* 82 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ +/* 84 */ 0x30, /* FC_BIND_CONTEXT */ + 0x44, /* Ctxt flags: in, no serialize, */ +/* 86 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 88 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 90 */ NdrFcShort( 0x44 ), /* 68 */ +/* 92 */ NdrFcShort( 0x0 ), /* 0 */ +/* 94 */ 0x40, /* Oi2 Flags: has ext, */ + 0x3, /* 3 */ +/* 96 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 98 */ NdrFcShort( 0x0 ), /* 0 */ +/* 100 */ NdrFcShort( 0x0 ), /* 0 */ +/* 102 */ NdrFcShort( 0x0 ), /* 0 */ +/* 104 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 106 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 108 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 110 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Parameter samplePeriod */ + +/* 112 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 114 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 116 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Parameter context */ + +/* 118 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 120 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 122 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Procedure SetSamplePeriod */ + +/* 124 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 126 */ NdrFcLong( 0x0 ), /* 0 */ +/* 130 */ NdrFcShort( 0x3 ), /* 3 */ +/* 132 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 134 */ 0x30, /* FC_BIND_CONTEXT */ + 0x44, /* Ctxt flags: in, no serialize, */ +/* 136 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 138 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 140 */ NdrFcShort( 0x34 ), /* 52 */ +/* 142 */ NdrFcShort( 0x0 ), /* 0 */ +/* 144 */ 0x40, /* Oi2 Flags: has ext, */ + 0x2, /* 2 */ +/* 146 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 148 */ NdrFcShort( 0x0 ), /* 0 */ +/* 150 */ NdrFcShort( 0x0 ), /* 0 */ +/* 152 */ NdrFcShort( 0x0 ), /* 0 */ +/* 154 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 156 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 158 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 160 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Parameter samplePeriod */ + +/* 162 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 164 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 166 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Procedure StopMetering */ + +/* 168 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 170 */ NdrFcLong( 0x0 ), /* 0 */ +/* 174 */ NdrFcShort( 0x4 ), /* 4 */ +/* 176 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 178 */ 0x30, /* FC_BIND_CONTEXT */ + 0x44, /* Ctxt flags: in, no serialize, */ +/* 180 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 182 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 184 */ NdrFcShort( 0x24 ), /* 36 */ +/* 186 */ NdrFcShort( 0x0 ), /* 0 */ +/* 188 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 190 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 192 */ NdrFcShort( 0x0 ), /* 0 */ +/* 194 */ NdrFcShort( 0x0 ), /* 0 */ +/* 196 */ NdrFcShort( 0x0 ), /* 0 */ +/* 198 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 200 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 202 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 204 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Procedure MeteringDataEvent */ + +/* 206 */ 0x34, /* FC_CALLBACK_HANDLE */ + 0x48, /* Old Flags: */ +/* 208 */ NdrFcLong( 0x0 ), /* 0 */ +/* 212 */ NdrFcShort( 0x0 ), /* 0 */ +/* 214 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 216 */ NdrFcShort( 0x20 ), /* 32 */ +/* 218 */ NdrFcShort( 0x0 ), /* 0 */ +/* 220 */ 0x40, /* Oi2 Flags: has ext, */ + 0x2, /* 2 */ +/* 222 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 224 */ NdrFcShort( 0x0 ), /* 0 */ +/* 226 */ NdrFcShort( 0x0 ), /* 0 */ +/* 228 */ NdrFcShort( 0x0 ), /* 0 */ +/* 230 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter data */ + +/* 232 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 234 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 236 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Parameter context */ + +/* 238 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 240 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 242 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + 0x0 + } + }; + +static const RpcInterface_MIDL_TYPE_FORMAT_STRING RpcInterface__MIDL_TypeFormatString = + { + 0, + { + NdrFcShort( 0x0 ), /* 0 */ +/* 2 */ + 0x11, 0x4, /* FC_RP [alloced_on_stack] */ +/* 4 */ NdrFcShort( 0x2 ), /* Offset= 2 (6) */ +/* 6 */ 0x30, /* FC_BIND_CONTEXT */ + 0xa4, /* Ctxt flags: via ptr, out, no serialize, */ +/* 8 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 10 */ + 0x11, 0x4, /* FC_RP [alloced_on_stack] */ +/* 12 */ NdrFcShort( 0x2 ), /* Offset= 2 (14) */ +/* 14 */ 0x30, /* FC_BIND_CONTEXT */ + 0xe5, /* Ctxt flags: via ptr, in, out, no serialize, can't be null */ +/* 16 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 18 */ 0x30, /* FC_BIND_CONTEXT */ + 0x45, /* Ctxt flags: in, no serialize, can't be null */ +/* 20 */ 0x0, /* 0 */ + 0x0, /* 0 */ + + 0x0 + } + }; + +static const unsigned short RpcInterface_FormatStringOffsetTable[] = + { + 0, + 36, + 74, + 124, + 168, + }; + + +static const unsigned short _callbackRpcInterface_FormatStringOffsetTable[] = + { + 206 + }; + + +static const MIDL_STUB_DESC RpcInterface_StubDesc = + { + (void *)& RpcInterface___RpcClientInterface, + MIDL_user_allocate, + MIDL_user_free, + &RpcInterface__MIDL_AutoBindHandle, + 0, + 0, + 0, + 0, + RpcInterface__MIDL_TypeFormatString.Format, + 1, /* -error bounds_check flag */ + 0x50002, /* Ndr library version */ + 0, + 0x801026e, /* MIDL Version 8.1.622 */ + 0, + 0, + 0, /* notify & notify_flag routine table */ + 0x1, /* MIDL flag */ + 0, /* cs routines */ + 0, /* proxy/server info */ + 0 + }; + +static const RPC_DISPATCH_FUNCTION RpcInterface_table[] = + { + NdrServerCall2, + 0 + }; +static const RPC_DISPATCH_TABLE RpcInterface_v1_0_DispatchTable = + { + 1, + (RPC_DISPATCH_FUNCTION*)RpcInterface_table + }; + +static const SERVER_ROUTINE RpcInterface_ServerRoutineTable[] = + { + (SERVER_ROUTINE)MeteringDataEvent + }; + +static const MIDL_SERVER_INFO RpcInterface_ServerInfo = + { + &RpcInterface_StubDesc, + RpcInterface_ServerRoutineTable, + RpcInterface__MIDL_ProcFormatString.Format, + _callbackRpcInterface_FormatStringOffsetTable, + 0, + 0, + 0, + 0}; +#if _MSC_VER >= 1200 +#pragma warning(pop) +#endif + + +#endif /* defined(_M_AMD64)*/ + diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface_h.h b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface_h.h new file mode 100644 index 00000000..98544da7 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface_h.h @@ -0,0 +1,103 @@ + + +/* this ALWAYS GENERATED file contains the definitions for the interfaces */ + + + /* File created by MIDL compiler version 8.01.0622 */ +/* at Mon Jan 18 19:14:07 2038 + */ +/* Compiler settings for RpcInterface.Idl: + Oicf, W1, Zp8, env=Win64 (32b run), target_arch=AMD64 8.01.0622 + protocol : dce , ms_ext, c_ext, robust + error checks: allocation ref bounds_check enum stub_data + VC __declspec() decoration level: + __declspec(uuid()), __declspec(selectany), __declspec(novtable) + DECLSPEC_UUID(), MIDL_INTERFACE() +*/ +/* @@MIDL_FILE_HEADING( ) */ + +#pragma warning( disable: 4049 ) /* more than 64k source lines */ + + +/* verify that the <rpcndr.h> version is high enough to compile this file*/ +#ifndef __REQUIRED_RPCNDR_H_VERSION__ +#define __REQUIRED_RPCNDR_H_VERSION__ 475 +#endif + +#include "rpc.h" +#include "rpcndr.h" + +#ifndef __RPCNDR_H_VERSION__ +#error this stub requires an updated version of <rpcndr.h> +#endif /* __RPCNDR_H_VERSION__ */ + + +#ifndef __RpcInterface_h_h__ +#define __RpcInterface_h_h__ + +#if defined(_MSC_VER) && (_MSC_VER >= 1020) +#pragma once +#endif + +/* Forward Declarations */ + +/* header files for imported files */ +#include "oaidl.h" + +#ifdef __cplusplus +extern "C"{ +#endif + + +#ifndef __RpcInterface_INTERFACE_DEFINED__ +#define __RpcInterface_INTERFACE_DEFINED__ + +/* interface RpcInterface */ +/* [unique][version][uuid] */ + +typedef /* [context_handle_noserialize][context_handle] */ void *PCONTEXT_HANDLE_TYPE; + +typedef /* [ref] */ PCONTEXT_HANDLE_TYPE *PPCONTEXT_HANDLE_TYPE; + +void RemoteOpen( + /* [in] */ handle_t hBinding, + /* [out] */ PPCONTEXT_HANDLE_TYPE pphContext); + +void RemoteClose( + /* [out][in] */ PPCONTEXT_HANDLE_TYPE pphContext); + +void StartMetering( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext, + /* [in] */ __int64 samplePeriod, + /* [optional][in] */ __int64 context); + +void SetSamplePeriod( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext, + /* [in] */ __int64 samplePeriod); + +void StopMetering( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext); + +/* [callback] */ void MeteringDataEvent( + /* [in] */ __int64 data, + /* [optional][in] */ __int64 context); + + + +extern RPC_IF_HANDLE RpcInterface_v1_0_c_ifspec; +extern RPC_IF_HANDLE RpcInterface_v1_0_s_ifspec; +#endif /* __RpcInterface_INTERFACE_DEFINED__ */ + +/* Additional Prototypes for ALL interfaces */ + +void __RPC_USER PCONTEXT_HANDLE_TYPE_rundown( PCONTEXT_HANDLE_TYPE ); + +/* end of Additional Prototypes */ + +#ifdef __cplusplus +} +#endif + +#endif + + diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface_s.c b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface_s.c new file mode 100644 index 00000000..89aa59bf --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcInterface_s.c @@ -0,0 +1,430 @@ + + +/* this ALWAYS GENERATED file contains the RPC server stubs */ + + + /* File created by MIDL compiler version 8.01.0622 */ +/* at Mon Jan 18 19:14:07 2038 + */ +/* Compiler settings for RpcInterface.Idl: + Oicf, W1, Zp8, env=Win64 (32b run), target_arch=AMD64 8.01.0622 + protocol : dce , ms_ext, c_ext, robust + error checks: allocation ref bounds_check enum stub_data + VC __declspec() decoration level: + __declspec(uuid()), __declspec(selectany), __declspec(novtable) + DECLSPEC_UUID(), MIDL_INTERFACE() +*/ +/* @@MIDL_FILE_HEADING( ) */ + +#if defined(_M_AMD64) + + +#pragma warning( disable: 4049 ) /* more than 64k source lines */ +#if _MSC_VER >= 1200 +#pragma warning(push) +#endif + +#pragma warning( disable: 4211 ) /* redefine extern to static */ +#pragma warning( disable: 4232 ) /* dllimport identity*/ +#pragma warning( disable: 4024 ) /* array to pointer mapping*/ + +#include <string.h> +#include "RpcInterface_h.h" + +#define TYPE_FORMAT_STRING_SIZE 23 +#define PROC_FORMAT_STRING_SIZE 245 +#define EXPR_FORMAT_STRING_SIZE 1 +#define TRANSMIT_AS_TABLE_SIZE 0 +#define WIRE_MARSHAL_TABLE_SIZE 0 + +typedef struct _RpcInterface_MIDL_TYPE_FORMAT_STRING + { + short Pad; + unsigned char Format[ TYPE_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_TYPE_FORMAT_STRING; + +typedef struct _RpcInterface_MIDL_PROC_FORMAT_STRING + { + short Pad; + unsigned char Format[ PROC_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_PROC_FORMAT_STRING; + +typedef struct _RpcInterface_MIDL_EXPR_FORMAT_STRING + { + long Pad; + unsigned char Format[ EXPR_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_EXPR_FORMAT_STRING; + + +static const RPC_SYNTAX_IDENTIFIER _RpcTransferSyntax = +{{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}}; + +extern const RpcInterface_MIDL_TYPE_FORMAT_STRING RpcInterface__MIDL_TypeFormatString; +extern const RpcInterface_MIDL_PROC_FORMAT_STRING RpcInterface__MIDL_ProcFormatString; +extern const RpcInterface_MIDL_EXPR_FORMAT_STRING RpcInterface__MIDL_ExprFormatString; + +/* Standard interface: RpcInterface, ver. 1.0, + GUID={0x906B0CE0,0xC70B,0x1067,{0xB3,0x17,0x00,0xDD,0x01,0x06,0x62,0xDA}} */ + + +extern const MIDL_SERVER_INFO RpcInterface_ServerInfo; + +extern const RPC_DISPATCH_TABLE RpcInterface_v1_0_DispatchTable; + +static const RPC_SERVER_INTERFACE RpcInterface___RpcServerInterface = + { + sizeof(RPC_SERVER_INTERFACE), + {{0x906B0CE0,0xC70B,0x1067,{0xB3,0x17,0x00,0xDD,0x01,0x06,0x62,0xDA}},{1,0}}, + {{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}}, + (RPC_DISPATCH_TABLE*)&RpcInterface_v1_0_DispatchTable, + 0, + 0, + 0, + &RpcInterface_ServerInfo, + 0x04000000 + }; +RPC_IF_HANDLE RpcInterface_v1_0_s_ifspec = (RPC_IF_HANDLE)& RpcInterface___RpcServerInterface; + +extern const MIDL_STUB_DESC RpcInterface_StubDesc; + + extern const MIDL_STUBLESS_PROXY_INFO RpcInterface_ProxyInfo; + +/* [callback] */ void MeteringDataEvent( + /* [in] */ __int64 data, + /* [optional][in] */ __int64 context) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[206], + data, + context); + +} + +extern const NDR_RUNDOWN RundownRoutines[]; + +#if !defined(__RPC_WIN64__) +#error Invalid build platform for this stub. +#endif + +static const RpcInterface_MIDL_PROC_FORMAT_STRING RpcInterface__MIDL_ProcFormatString = + { + 0, + { + + /* Procedure RemoteOpen */ + + 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 2 */ NdrFcLong( 0x0 ), /* 0 */ +/* 6 */ NdrFcShort( 0x0 ), /* 0 */ +/* 8 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 10 */ 0x32, /* FC_BIND_PRIMITIVE */ + 0x0, /* 0 */ +/* 12 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 14 */ NdrFcShort( 0x0 ), /* 0 */ +/* 16 */ NdrFcShort( 0x38 ), /* 56 */ +/* 18 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 20 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 22 */ NdrFcShort( 0x0 ), /* 0 */ +/* 24 */ NdrFcShort( 0x0 ), /* 0 */ +/* 26 */ NdrFcShort( 0x0 ), /* 0 */ +/* 28 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter pphContext */ + +/* 30 */ NdrFcShort( 0x110 ), /* Flags: out, simple ref, */ +/* 32 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 34 */ NdrFcShort( 0x6 ), /* Type Offset=6 */ + + /* Procedure RemoteClose */ + +/* 36 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 38 */ NdrFcLong( 0x0 ), /* 0 */ +/* 42 */ NdrFcShort( 0x1 ), /* 1 */ +/* 44 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 46 */ 0x30, /* FC_BIND_CONTEXT */ + 0xe4, /* Ctxt flags: via ptr, in, out, no serialize, */ +/* 48 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 50 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 52 */ NdrFcShort( 0x38 ), /* 56 */ +/* 54 */ NdrFcShort( 0x38 ), /* 56 */ +/* 56 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 58 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 60 */ NdrFcShort( 0x0 ), /* 0 */ +/* 62 */ NdrFcShort( 0x0 ), /* 0 */ +/* 64 */ NdrFcShort( 0x0 ), /* 0 */ +/* 66 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter pphContext */ + +/* 68 */ NdrFcShort( 0x118 ), /* Flags: in, out, simple ref, */ +/* 70 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 72 */ NdrFcShort( 0xe ), /* Type Offset=14 */ + + /* Procedure StartMetering */ + +/* 74 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 76 */ NdrFcLong( 0x0 ), /* 0 */ +/* 80 */ NdrFcShort( 0x2 ), /* 2 */ +/* 82 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ +/* 84 */ 0x30, /* FC_BIND_CONTEXT */ + 0x44, /* Ctxt flags: in, no serialize, */ +/* 86 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 88 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 90 */ NdrFcShort( 0x44 ), /* 68 */ +/* 92 */ NdrFcShort( 0x0 ), /* 0 */ +/* 94 */ 0x40, /* Oi2 Flags: has ext, */ + 0x3, /* 3 */ +/* 96 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 98 */ NdrFcShort( 0x0 ), /* 0 */ +/* 100 */ NdrFcShort( 0x0 ), /* 0 */ +/* 102 */ NdrFcShort( 0x0 ), /* 0 */ +/* 104 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 106 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 108 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 110 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Parameter samplePeriod */ + +/* 112 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 114 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 116 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Parameter context */ + +/* 118 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 120 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 122 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Procedure SetSamplePeriod */ + +/* 124 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 126 */ NdrFcLong( 0x0 ), /* 0 */ +/* 130 */ NdrFcShort( 0x3 ), /* 3 */ +/* 132 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 134 */ 0x30, /* FC_BIND_CONTEXT */ + 0x44, /* Ctxt flags: in, no serialize, */ +/* 136 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 138 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 140 */ NdrFcShort( 0x34 ), /* 52 */ +/* 142 */ NdrFcShort( 0x0 ), /* 0 */ +/* 144 */ 0x40, /* Oi2 Flags: has ext, */ + 0x2, /* 2 */ +/* 146 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 148 */ NdrFcShort( 0x0 ), /* 0 */ +/* 150 */ NdrFcShort( 0x0 ), /* 0 */ +/* 152 */ NdrFcShort( 0x0 ), /* 0 */ +/* 154 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 156 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 158 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 160 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Parameter samplePeriod */ + +/* 162 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 164 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 166 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Procedure StopMetering */ + +/* 168 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 170 */ NdrFcLong( 0x0 ), /* 0 */ +/* 174 */ NdrFcShort( 0x4 ), /* 4 */ +/* 176 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 178 */ 0x30, /* FC_BIND_CONTEXT */ + 0x44, /* Ctxt flags: in, no serialize, */ +/* 180 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 182 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 184 */ NdrFcShort( 0x24 ), /* 36 */ +/* 186 */ NdrFcShort( 0x0 ), /* 0 */ +/* 188 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 190 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 192 */ NdrFcShort( 0x0 ), /* 0 */ +/* 194 */ NdrFcShort( 0x0 ), /* 0 */ +/* 196 */ NdrFcShort( 0x0 ), /* 0 */ +/* 198 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 200 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 202 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 204 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Procedure MeteringDataEvent */ + +/* 206 */ 0x34, /* FC_CALLBACK_HANDLE */ + 0x48, /* Old Flags: */ +/* 208 */ NdrFcLong( 0x0 ), /* 0 */ +/* 212 */ NdrFcShort( 0x0 ), /* 0 */ +/* 214 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 216 */ NdrFcShort( 0x20 ), /* 32 */ +/* 218 */ NdrFcShort( 0x0 ), /* 0 */ +/* 220 */ 0x40, /* Oi2 Flags: has ext, */ + 0x2, /* 2 */ +/* 222 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 224 */ NdrFcShort( 0x0 ), /* 0 */ +/* 226 */ NdrFcShort( 0x0 ), /* 0 */ +/* 228 */ NdrFcShort( 0x0 ), /* 0 */ +/* 230 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter data */ + +/* 232 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 234 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 236 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Parameter context */ + +/* 238 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 240 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 242 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + 0x0 + } + }; + +static const RpcInterface_MIDL_TYPE_FORMAT_STRING RpcInterface__MIDL_TypeFormatString = + { + 0, + { + NdrFcShort( 0x0 ), /* 0 */ +/* 2 */ + 0x11, 0x4, /* FC_RP [alloced_on_stack] */ +/* 4 */ NdrFcShort( 0x2 ), /* Offset= 2 (6) */ +/* 6 */ 0x30, /* FC_BIND_CONTEXT */ + 0xa4, /* Ctxt flags: via ptr, out, no serialize, */ +/* 8 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 10 */ + 0x11, 0x4, /* FC_RP [alloced_on_stack] */ +/* 12 */ NdrFcShort( 0x2 ), /* Offset= 2 (14) */ +/* 14 */ 0x30, /* FC_BIND_CONTEXT */ + 0xe5, /* Ctxt flags: via ptr, in, out, no serialize, can't be null */ +/* 16 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 18 */ 0x30, /* FC_BIND_CONTEXT */ + 0x45, /* Ctxt flags: in, no serialize, can't be null */ +/* 20 */ 0x0, /* 0 */ + 0x0, /* 0 */ + + 0x0 + } + }; + +static const NDR_RUNDOWN RundownRoutines[] = + { + PCONTEXT_HANDLE_TYPE_rundown + }; + + +static const unsigned short RpcInterface_FormatStringOffsetTable[] = + { + 0, + 36, + 74, + 124, + 168, + }; + + +static const unsigned short _callbackRpcInterface_FormatStringOffsetTable[] = + { + 206 + }; + + +static const MIDL_STUB_DESC RpcInterface_StubDesc = + { + (void *)& RpcInterface___RpcServerInterface, + MIDL_user_allocate, + MIDL_user_free, + 0, + RundownRoutines, + 0, + 0, + 0, + RpcInterface__MIDL_TypeFormatString.Format, + 1, /* -error bounds_check flag */ + 0x50002, /* Ndr library version */ + 0, + 0x801026e, /* MIDL Version 8.1.622 */ + 0, + 0, + 0, /* notify & notify_flag routine table */ + 0x1, /* MIDL flag */ + 0, /* cs routines */ + 0, /* proxy/server info */ + 0 + }; + +static const RPC_DISPATCH_FUNCTION RpcInterface_table[] = + { + NdrServerCall2, + NdrServerCall2, + NdrServerCall2, + NdrServerCall2, + NdrServerCall2, + 0 + }; +static const RPC_DISPATCH_TABLE RpcInterface_v1_0_DispatchTable = + { + 5, + (RPC_DISPATCH_FUNCTION*)RpcInterface_table + }; + +static const SERVER_ROUTINE RpcInterface_ServerRoutineTable[] = + { + (SERVER_ROUTINE)RemoteOpen, + (SERVER_ROUTINE)RemoteClose, + (SERVER_ROUTINE)StartMetering, + (SERVER_ROUTINE)SetSamplePeriod, + (SERVER_ROUTINE)StopMetering, + }; + +static const MIDL_SERVER_INFO RpcInterface_ServerInfo = + { + &RpcInterface_StubDesc, + RpcInterface_ServerRoutineTable, + RpcInterface__MIDL_ProcFormatString.Format, + RpcInterface_FormatStringOffsetTable, + 0, + 0, + 0, + 0}; +#if _MSC_VER >= 1200 +#pragma warning(pop) +#endif + + +#endif /* defined(_M_AMD64)*/ + diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.cpp b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.cpp new file mode 100644 index 00000000..0cad3578 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.cpp @@ -0,0 +1,320 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "stdafx.h" +#include <stdlib.h> +#include <stdio.h> +#include <iostream> +#include "RpcInterface_h.h" +#include <windows.h> + +#include <sddl.h> +#include <securitybaseapi.h> +#include <AclAPI.h> +#include "RpcServer.h" + +using namespace RpcServer; + +#define DEFAULT_METERING_PERIOD 100 + +bool ShutdownRequested; +static RPC_BINDING_VECTOR* BindingVector = nullptr; + +void FreeSidArray(__inout_ecount(cSIDs) PSID* pSIDs, ULONG cSIDs) +{ + if (pSIDs != nullptr) + { + for (ULONG i = 0; i < cSIDs; i++) + { + LocalFree(pSIDs[i]); + + pSIDs[i] = nullptr; + } + + LocalFree(pSIDs); + + pSIDs = nullptr; + cSIDs = 0; + } +} + +// +// Routine to create RPC server and listen to incoming RPC calls +// +DWORD RpcServerStart() +{ + DWORD hResult = S_OK; + WCHAR* protocolSequence = L"ncalrpc"; + unsigned int minCalls = 1; + unsigned int dontWait = false; + ShutdownRequested = false; + + SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY; + PSID everyoneSid = nullptr; + PSID* capabilitySids = nullptr; + DWORD capabilitySidCount = 0; + PSID* capabilityGroupSids = nullptr; + DWORD capabilityGroupSidCount = 0; + EXPLICIT_ACCESS ea[2] = {}; + PACL acl = nullptr; + SECURITY_DESCRIPTOR rpcSecurityDescriptor = {}; + + // When creating the RPC endpoint we want it to allow connections from any UWA that contains + // the custom capability SID in its process token. When a UWA declares the custom capability + // in its app manifest, it will later contain the SID form of that custom capability in its + // process token at runtime. By default, RPC endpoints don't allow UWAs (AppContainer processes) + // to connect to them, so we need to set the security on the endpoint to allow access to UWAs with the + // custom capability. + // + // To do this we'll perform the following steps: + // 1) Convert the custom capability name to a SID + // 2) Create a security descriptor using that SID, as well as other needed SIDs. This sample shows how to allow + // all 'non UWAs' access as well as UWAs containing the custom capability SID. + // 3) Create the RPC endpoint using that security descriptor + // + // To create the security descriptor we're roughly following this MSDN sample: + // https://msdn.microsoft.com/en-us/library/windows/desktop/aa446595(v=vs.85).aspx + + // Get the SID form of the custom capability. In this case we only expect one SID and + // we don't care about the capability group. + //INSERT DERIVE CAPABILTY SIDS FROM NAME HERE + + // Get the SID that represents 'everyone' (this doesn't include AppContainers) + if (!AllocateAndInitializeSid( + &SIDAuthWorld, 1, + SECURITY_WORLD_RID, + 0, 0, 0, 0, 0, 0, 0, + &everyoneSid)) + { + hResult = GetLastError(); + goto end; + } + + // Now create the Access Control List (ACL) for the Security descriptor + + // Everyone GENERIC_ALL access + ea[0].grfAccessMode = SET_ACCESS; + ea[0].grfAccessPermissions = GENERIC_ALL; + ea[0].grfInheritance = NO_INHERITANCE; + ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; + ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; + ea[0].Trustee.ptstrName = static_cast<LPWSTR>(everyoneSid); + + // Custom capability GENERIC_ALL access + ea[1].grfAccessMode = SET_ACCESS; + ea[1].grfAccessPermissions = GENERIC_ALL; + ea[1].grfInheritance = NO_INHERITANCE; + ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID; + ea[1].Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN; + ea[1].Trustee.ptstrName = static_cast<LPWSTR>(everyoneSid); + + hResult = SetEntriesInAcl(ARRAYSIZE(ea), ea, nullptr, &acl); + + if (hResult != ERROR_SUCCESS) + { + goto end; + } + + // Initialize an empty security descriptor + if (!InitializeSecurityDescriptor(&rpcSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION)) + { + hResult = GetLastError(); + goto end; + } + + // Assign the ACL to the security descriptor + if (!SetSecurityDescriptorDacl(&rpcSecurityDescriptor, TRUE, acl, FALSE)) + { + hResult = GetLastError(); + goto end; + } + + // + // Bind to LRPC using dynamic endpoints + // + hResult = RpcServerUseProtseqEp( + reinterpret_cast<RPC_WSTR>(protocolSequence), + RPC_C_PROTSEQ_MAX_REQS_DEFAULT, + reinterpret_cast<RPC_WSTR>(RPC_STATIC_ENDPOINT), + &rpcSecurityDescriptor); + + if (hResult != S_OK) + { + goto end; + } + + hResult = RpcServerRegisterIf3( + RpcInterface_v1_0_s_ifspec, + nullptr, + nullptr, + RPC_IF_AUTOLISTEN | RPC_IF_ALLOW_LOCAL_ONLY, + RPC_C_LISTEN_MAX_CALLS_DEFAULT, + 0, + nullptr, + &rpcSecurityDescriptor); + + if (hResult != S_OK) + { + goto end; + } + + hResult = RpcServerInqBindings(&BindingVector); + + if (hResult != S_OK) + { + goto end; + } + + hResult = RpcEpRegister( + RpcInterface_v1_0_s_ifspec, + BindingVector, + nullptr, + nullptr); + + if (hResult != S_OK) + { + goto end; + } + + hResult = RpcServerListen( + minCalls, + RPC_C_LISTEN_MAX_CALLS_DEFAULT, + dontWait); + + if (hResult == RPC_S_ALREADY_LISTENING) + { + hResult = RPC_S_OK; + } + +end: + + // Cleanup sids + FreeSidArray(capabilityGroupSids, capabilityGroupSidCount); + FreeSidArray(capabilitySids, capabilitySidCount); + + if (everyoneSid != nullptr) + { + FreeSid(everyoneSid); + } + + // cleanup acl + if (acl != nullptr) + { + LocalFree(acl); + } + + return hResult; +} + +// +// Notify rpc server to stop listening to incoming rpc calls +// +void RpcServerDisconnect() +{ + DWORD hResult = S_OK; + ShutdownRequested = true; + hResult = RpcServerUnregisterIf(RpcInterface_v1_0_s_ifspec, nullptr, 0); + + RpcEpUnregister(RpcInterface_v1_0_s_ifspec, BindingVector, nullptr); + + if (BindingVector != nullptr) + { + RpcBindingVectorFree(&BindingVector); + BindingVector = nullptr; + } +} + +// +// Rpc method to retrieve client context handle +// +void RemoteOpen( + _In_ handle_t hBinding, + _Out_ PPCONTEXT_HANDLE_TYPE pphContext) +{ + *pphContext = static_cast<PCONTEXT_HANDLE_TYPE *>(midl_user_allocate(sizeof(METERING_CONTEXT))); + METERING_CONTEXT* meteringContext = static_cast<METERING_CONTEXT *>(*pphContext); + meteringContext->metering = new Metering(DEFAULT_METERING_PERIOD); +} + +// +// Rpc method to close the client context handle +// +void RemoteClose(_Inout_ PPCONTEXT_HANDLE_TYPE pphContext) +{ + if (*pphContext == nullptr) + { + //Log error, client tried to close a NULL handle. + return; + } + + METERING_CONTEXT* meteringContext = static_cast<METERING_CONTEXT *>(*pphContext); + delete meteringContext->metering; + MIDL_user_free(meteringContext); + + // This tells the run-time, when it is marshalling the out + // parameters, that the context handle has been closed normally. + *pphContext = nullptr; +} + +// +// Routine to cleanup client context when client has died with active +// connection with server +// +void __RPC_USER PCONTEXT_HANDLE_TYPE_rundown( + _In_ PCONTEXT_HANDLE_TYPE phContext) +{ + StopMetering(phContext); + RemoteClose(&phContext); +} + +#pragma region METERING_RPCROUTINES + +void StartMetering( + _In_ PCONTEXT_HANDLE_TYPE phContext, + _In_ __int64 period, + _In_ __int64 context) +{ + std::cout << "start metering" << std::endl; + METERING_CONTEXT* meteringContext = static_cast<METERING_CONTEXT *>(phContext); + meteringContext->metering->StartMetering(period, context); + std::cout << "done metering" << std::endl; +} + +void SetSamplePeriod( + _In_ PCONTEXT_HANDLE_TYPE phContext, + _In_ __int64 period) +{ + METERING_CONTEXT* meteringContext = static_cast<METERING_CONTEXT *>(phContext); + meteringContext->metering->SetSamplePeriod(period); +} + + +void StopMetering(_In_ PCONTEXT_HANDLE_TYPE phContext) +{ + METERING_CONTEXT* meteringContext = static_cast<METERING_CONTEXT *>(phContext); + meteringContext->metering->StopMetering(); +} + +#pragma endregion METERING_RPCROUTINES + +/******************************************************/ +/* MIDL allocate and free */ +/******************************************************/ + +void __RPC_FAR * __RPC_USER midl_user_allocate(_In_ size_t len) +{ + return(malloc(len)); +} + +void __RPC_USER midl_user_free(_In_ void __RPC_FAR* ptr) +{ + free(ptr); +} diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.h b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.h new file mode 100644 index 00000000..bc7294db --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.h @@ -0,0 +1,16 @@ +#include "metering.h" + +#define RPC_STATIC_ENDPOINT L"HsaSampleRpcEndpoint" + +// Client context used for making rpc calls using context handle +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa378674(v=vs.85).aspx +typedef struct +{ + RpcServer::Metering* metering; +} METERING_CONTEXT; + +// Create a rpc server endpoint and listen to incoming rpc calls +DWORD RpcServerStart(); + +// Signal the rpc server to stop listening to incoming rpc calls +void RpcServerDisconnect(); diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.vcxproj b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.vcxproj new file mode 100644 index 00000000..b5c043dc --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.vcxproj @@ -0,0 +1,284 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|ARM"> + <Configuration>Debug</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM"> + <Configuration>Release</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{ADFC4322-5F0E-5BFD-83DA-19B35EFD513B}</ProjectGuid> + <Keyword>Win32Proj</Keyword> + <RootNamespace>RpcServer</RootNamespace> + <WindowsTargetPlatformVersion>10.0.16299.0</WindowsTargetPlatformVersion> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>v141</PlatformToolset> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>v141</PlatformToolset> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>v141</PlatformToolset> + <WholeProgramOptimization>true</WholeProgramOptimization> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>v141</PlatformToolset> + <WholeProgramOptimization>true</WholeProgramOptimization> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>v141</PlatformToolset> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>v141</PlatformToolset> + <WholeProgramOptimization>true</WholeProgramOptimization> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="Shared"> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <LinkIncremental>true</LinkIncremental> + <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> + <IntDir>$(Platform)\$(Configuration)\</IntDir> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> + <LinkIncremental>true</LinkIncremental> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <LinkIncremental>true</LinkIncremental> + <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <LinkIncremental>false</LinkIncremental> + <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> + <IntDir>$(Platform)\$(Configuration)\</IntDir> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> + <LinkIncremental>false</LinkIncremental> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <LinkIncremental>false</LinkIncremental> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <PrecompiledHeader>Use</PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <Optimization>Disabled</Optimization> + <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <SDLCheck>true</SDLCheck> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(OutDir)</AdditionalIncludeDirectories> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;%(AdditionalDependencies);rpcrt4.lib</AdditionalDependencies> + <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries> + <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries);kernel32.lib;user32.lib;shell32.lib;gdi32.lib</IgnoreSpecificDefaultLibraries> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> + <ClCompile> + <PrecompiledHeader>Use</PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <Optimization>Disabled</Optimization> + <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <SDLCheck>true</SDLCheck> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(OutDir)</AdditionalIncludeDirectories> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;%(AdditionalDependencies);rpcrt4.lib</AdditionalDependencies> + <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries> + <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries);kernel32.lib;user32.lib;shell32.lib;gdi32.lib</IgnoreSpecificDefaultLibraries> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <PrecompiledHeader>Use</PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <Optimization>Disabled</Optimization> + <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <SDLCheck>true</SDLCheck> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(OutDir)</AdditionalIncludeDirectories> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;%(AdditionalDependencies);rpcrt4.lib</AdditionalDependencies> + <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries> + <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries);kernel32.lib;user32.lib;shell32.lib;gdi32.lib</IgnoreSpecificDefaultLibraries> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <ClCompile> + <WarningLevel>Level3</WarningLevel> + <PrecompiledHeader>Use</PrecompiledHeader> + <Optimization>MaxSpeed</Optimization> + <FunctionLevelLinking>true</FunctionLevelLinking> + <IntrinsicFunctions>true</IntrinsicFunctions> + <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <SDLCheck>true</SDLCheck> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(OutDir)</AdditionalIncludeDirectories> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <EnableCOMDATFolding>true</EnableCOMDATFolding> + <OptimizeReferences>true</OptimizeReferences> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;%(AdditionalDependencies);ucrt.lib;rpcrt4.lib;libcmt.lib;libvcruntime.lib</AdditionalDependencies> + <IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries> + <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries);kernel32.lib;user32.lib;shell32.lib;gdi32.lib</IgnoreSpecificDefaultLibraries> + <AdditionalOptions>/VERBOSE %(AdditionalOptions)</AdditionalOptions> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> + <ClCompile> + <WarningLevel>Level3</WarningLevel> + <PrecompiledHeader>Use</PrecompiledHeader> + <Optimization>MaxSpeed</Optimization> + <FunctionLevelLinking>true</FunctionLevelLinking> + <IntrinsicFunctions>true</IntrinsicFunctions> + <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions);</PreprocessorDefinitions> + <SDLCheck>true</SDLCheck> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(OutDir)</AdditionalIncludeDirectories> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <EnableCOMDATFolding>true</EnableCOMDATFolding> + <OptimizeReferences>true</OptimizeReferences> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;%(AdditionalDependencies);ucrt.lib;rpcrt4.lib;libcmt.lib;libvcruntime.lib</AdditionalDependencies> + <IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries> + <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries);kernel32.lib;user32.lib;shell32.lib;gdi32.lib</IgnoreSpecificDefaultLibraries> + <AdditionalOptions>/VERBOSE %(AdditionalOptions)</AdditionalOptions> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <WarningLevel>Level3</WarningLevel> + <PrecompiledHeader>Use</PrecompiledHeader> + <Optimization>MaxSpeed</Optimization> + <FunctionLevelLinking>true</FunctionLevelLinking> + <IntrinsicFunctions>true</IntrinsicFunctions> + <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <SDLCheck>true</SDLCheck> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(OutDir)</AdditionalIncludeDirectories> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + </ClCompile> + <Link> + <SubSystem>Console</SubSystem> + <EnableCOMDATFolding>true</EnableCOMDATFolding> + <OptimizeReferences>true</OptimizeReferences> + <GenerateDebugInformation>true</GenerateDebugInformation> + <AdditionalDependencies>onecoreuap.lib;%(AdditionalDependencies);ucrt.lib;rpcrt4.lib;libcmt.lib;libvcruntime.lib</AdditionalDependencies> + <IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries> + <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries);kernel32.lib;user32.lib;shell32.lib;gdi32.lib</IgnoreSpecificDefaultLibraries> + <AdditionalOptions>/VERBOSE %(AdditionalOptions)</AdditionalOptions> + </Link> + </ItemDefinitionGroup> + <ItemGroup> + <ClInclude Include="Metering.h" /> + <ClInclude Include="RpcServer.h" /> + <ClInclude Include="SampleService.h" /> + <ClInclude Include="ServiceBase.h" /> + <ClInclude Include="ServiceInstaller.h" /> + <ClInclude Include="stdafx.h" /> + <ClInclude Include="targetver.h" /> + </ItemGroup> + <ItemGroup> + <ClCompile Include="RpcInterface_s.c"> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader> + </ClCompile> + <ClCompile Include="HsaService.cpp" /> + <ClCompile Include="Metering.cpp" /> + <ClCompile Include="RpcServer.cpp" /> + <ClCompile Include="SampleService.cpp" /> + <ClCompile Include="ServiceBase.cpp" /> + <ClCompile Include="ServiceInstaller.cpp" /> + <ClCompile Include="stdafx.cpp"> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader> + </ClCompile> + </ItemGroup> + <ItemGroup> + <None Include="RpcInterface.acf" /> + </ItemGroup> + <ItemGroup> + <Midl Include="RpcInterface.Idl" /> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.vcxproj.filters b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.vcxproj.filters new file mode 100644 index 00000000..9644ad4e --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/RpcServer.vcxproj.filters @@ -0,0 +1,76 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Source Files"> + <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> + <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> + </Filter> + <Filter Include="Header Files"> + <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> + <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions> + </Filter> + <Filter Include="Resource Files"> + <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> + <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> + </Filter> + </ItemGroup> + <ItemGroup> + <ClInclude Include="stdafx.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="targetver.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="Metering.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="RpcServer.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="SampleService.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="ServiceBase.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="ServiceInstaller.h"> + <Filter>Header Files</Filter> + </ClInclude> + </ItemGroup> + <ItemGroup> + <ClCompile Include="stdafx.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="HsaService.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="Metering.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="RpcServer.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="SampleService.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="ServiceBase.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="ServiceInstaller.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="RpcInterface_s.c"> + <Filter>Source Files</Filter> + </ClCompile> + </ItemGroup> + <ItemGroup> + <None Include="RpcInterface.acf"> + <Filter>Source Files</Filter> + </None> + </ItemGroup> + <ItemGroup> + <Midl Include="RpcInterface.Idl"> + <Filter>Source Files</Filter> + </Midl> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/SampleService.cpp b/general/WinHEC 2017 Lab/Toaster Driver/Service/SampleService.cpp new file mode 100644 index 00000000..793a7009 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/SampleService.cpp @@ -0,0 +1,155 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "stdafx.h" + +#pragma region Includes +#include "SampleService.h" +#include "RpcServer.h" +#include <Evntrace.h> +#pragma endregion + +CSampleService::CSampleService( + PWSTR pszServiceName, + BOOL fCanStop, + BOOL fCanShutdown, + BOOL fCanPauseContinue) + : CServiceBase(pszServiceName, fCanStop, fCanShutdown, fCanPauseContinue) +{ +} + +void CSampleService::WriteEventLogEntry(PWSTR pszMessage, BYTE bLevel) +{ + if (IsConsoleRun()) + { + wprintf(L"%d: %ls\n", bLevel, pszMessage); + } + __super::WriteEventLogEntry(pszMessage, bLevel); +} + +CSampleService::~CSampleService(void) +{ +} + +// +// This is the thread pool work callback function. +// +VOID CALLBACK ServiceWorkerThread( + _In_ PTP_CALLBACK_INSTANCE /*Instance*/, + _In_ PVOID Parameter, + _In_ PTP_WORK /*Work*/) +{ + // + // Do something when the work callback is invoked. + // + { + _int64 status = RpcServerStart(); + if (status) + { + CSampleService* sampleService = static_cast<CSampleService *>(Parameter); + sampleService->Stop(); + } + } + + return; +} + +// +// FUNCTION: CSampleService::OnStart(DWORD, LPWSTR *) +// +// PURPOSE: The function is executed when a Start command is sent to the +// service by the SCM or when the operating system starts (for a service +// that starts automatically). It specifies actions to take when the +// service starts. In this code sample, OnStart logs a service-start +// message to the Application log, and queues the main service function for +// execution in a thread pool worker thread. +// +// PARAMETERS: +// * dwArgc - number of command line arguments +// * lpszArgv - array of command line arguments +// +// NOTE: A service application is designed to be long running. Therefore, +// it usually polls or monitors something in the system. The monitoring is +// set up in the OnStart method. However, OnStart does not actually do the +// monitoring. The OnStart method must return to the operating system after +// the service's operation has begun. It must not loop forever or block. To +// set up a simple monitoring mechanism, one general solution is to create +// a timer in OnStart. The timer would then raise events in your code +// periodically, at which time your service could do its monitoring. The +// other solution is to spawn a new thread to perform the main service +// functions, which is demonstrated in this code sample. +// +void CSampleService::OnStart( + _In_ DWORD dwArgc, + _In_ LPWSTR *lpszArgv) +{ + // Log a service start message to the Application log. + WriteEventLogEntry(L"CppWindowsService in OnStart", TRACE_LEVEL_INFORMATION); + + // Queue the main service function for execution in a worker thread. + PTP_WORK_CALLBACK workcallback = ServiceWorkerThread; + m_work = CreateThreadpoolWork(workcallback, this, nullptr); + + if (NULL == m_work) + { + // TODO: Capture get last error + WriteEventLogEntry(L"CreateThreadpoolWork failed", TRACE_LEVEL_ERROR); + } + + // + // Submit the work to the pool. Because this was a pre-allocated + // work item (using CreateThreadpoolWork), it is guaranteed to execute. + // + SubmitThreadpoolWork(m_work); +} + +// +// FUNCTION: CSampleService::ConsoleRun() +// +// PURPOSE: The function is executed to simulate OnStart in +// console mode. +// +void CSampleService::ConsoleRun() +{ + m_runningInConsole = true; + + WriteEventLogEntry(L"Starting Rpc Server..", TRACE_LEVEL_INFORMATION); + long status = RpcServerStart(); + + if (status) + { + printf_s("RpcServerConnect returned: 0x%x\n", status); + WriteEventLogEntry(L"Starting Rpc Server..", TRACE_LEVEL_INFORMATION); + exit(static_cast<int>(status)); + } +} + +// +// FUNCTION: CSampleService::OnStop() +// +// PURPOSE: The function is executed when a Stop command is sent to the +// service by SCM. It specifies actions to take when a service stops +// running. In this code sample, OnStop logs a service-stop message to the +// Application log, and waits for the finish of the main service function. +// +// COMMENTS: +// Be sure to periodically call ReportServiceStatus() with +// SERVICE_STOP_PENDING if the procedure is going to take long time. +// +void CSampleService::OnStop() +{ + // Log a service stop message to the Application log. + WriteEventLogEntry(L"CppWindowsService in OnStop", TRACE_LEVEL_INFORMATION); + + // Instruct server to stop listening to remote procedure calls and + // unregister rpc interface + RpcServerDisconnect(); +}
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/SampleService.h b/general/WinHEC 2017 Lab/Toaster Driver/Service/SampleService.h new file mode 100644 index 00000000..04621b3e --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/SampleService.h @@ -0,0 +1,46 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +// Provides a sample service class that derives from the service base class - +// CServiceBase. The sample service logs the service start and stop +// information to the Application event log, and shows how to run the main +// function of the service in a thread pool worker thread. + +#pragma once + +#include "ServiceBase.h" + +class CSampleService : public CServiceBase +{ +public: + + CSampleService(PWSTR pszServiceName, + BOOL fCanStop = TRUE, + BOOL fCanShutdown = TRUE, + BOOL fCanPauseContinue = FALSE); + void ConsoleRun(); + bool IsConsoleRun() + { + return m_runningInConsole; + } + void WriteEventLogEntry(PWSTR pszMessage, BYTE bLevel) override; + virtual ~CSampleService(void); + +protected: + + virtual void OnStart(DWORD dwArgc, PWSTR *pszArgv) override; + virtual void OnStop() override; + + +private: + PTP_WORK m_work = nullptr; + bool m_runningInConsole = false; +};
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceBase.cpp b/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceBase.cpp new file mode 100644 index 00000000..117d740c --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceBase.cpp @@ -0,0 +1,566 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "stdafx.h" +#pragma region Includes + +#include "ServiceBase.h" +#include <assert.h> +#include <strsafe.h> +#include <evntprov.h> +#include <Evntrace.h> +#pragma endregion + +// +// HSA Service trace event provider +// {BE2E880E-F79F-4C30-9C95-09F003A0A7EA} +// +EXTERN_C __declspec(selectany) const GUID HSA_SERVICE_PROVIDER_GUID = { 0xbe2e880e, 0xf79f, 0x4c30,{ 0x9c, 0x95, 0x9, 0xf0, 0x3, 0xa0, 0xa7, 0xea } }; + +#pragma region Static Members + +// Initialize the singleton service instance. +CServiceBase *CServiceBase::s_service = nullptr; + + +// +// FUNCTION: CServiceBase::Run(CServiceBase &) +// +// PURPOSE: Register the executable for a service with the Service Control +// Manager (SCM). After you call Run(ServiceBase), the SCM issues a Start +// command, which results in a call to the OnStart method in the service. +// This method blocks until the service has stopped. +// +// PARAMETERS: +// * service - the reference to a CServiceBase object. It will become the +// singleton service instance of this service application. +// +// RETURN VALUE: If the function succeeds, the return value is TRUE. If the +// function fails, the return value is FALSE. To get extended error +// information, call GetLastError. +// +BOOL CServiceBase::Run(CServiceBase &service) +{ + s_service = &service; + + SERVICE_TABLE_ENTRY serviceTable[] = + { + { service.m_name, ServiceMain }, + { nullptr, nullptr } + }; + + // Connects the main thread of a service process to the service control + // manager, which causes the thread to be the service control dispatcher + // thread for the calling process. This call returns when the service has + // stopped. The process should simply terminate when the call returns. + return StartServiceCtrlDispatcher(serviceTable); +} + + +// +// FUNCTION: CServiceBase::ServiceMain(DWORD, PWSTR *) +// +// PURPOSE: Entry point for the service. It registers the handler function +// for the service and starts the service. +// +// PARAMETERS: +// * dwArgc - number of command line arguments +// * lpszArgv - array of command line arguments +// +void WINAPI CServiceBase::ServiceMain(DWORD dwArgc, PWSTR *pszArgv) +{ + assert(s_service != NULL); + + // Register the handler function for the service + s_service->m_statusHandle = RegisterServiceCtrlHandler( + s_service->m_name, ServiceCtrlHandler); + + if (s_service->m_statusHandle == NULL) + { + throw GetLastError(); + } + + // Start the service. + s_service->Start(dwArgc, pszArgv); +} + + +// +// FUNCTION: CServiceBase::ServiceCtrlHandler(DWORD) +// +// PURPOSE: The function is called by the SCM whenever a control code is +// sent to the service. +// +// PARAMETERS: +// * dwCtrlCode - the control code. This parameter can be one of the +// following values: +// +// SERVICE_CONTROL_CONTINUE +// SERVICE_CONTROL_INTERROGATE +// SERVICE_CONTROL_NETBINDADD +// SERVICE_CONTROL_NETBINDDISABLE +// SERVICE_CONTROL_NETBINDREMOVE +// SERVICE_CONTROL_PARAMCHANGE +// SERVICE_CONTROL_PAUSE +// SERVICE_CONTROL_SHUTDOWN +// SERVICE_CONTROL_STOP +// +// This parameter can also be a user-defined control code ranges from 128 +// to 255. +// +void WINAPI CServiceBase::ServiceCtrlHandler(DWORD dwCtrl) +{ + switch (dwCtrl) + { + case SERVICE_CONTROL_STOP: s_service->Stop(); break; + case SERVICE_CONTROL_PAUSE: s_service->Pause(); break; + case SERVICE_CONTROL_CONTINUE: s_service->Continue(); break; + case SERVICE_CONTROL_SHUTDOWN: s_service->Shutdown(); break; + case SERVICE_CONTROL_INTERROGATE: break; + default: break; + } +} + +#pragma endregion + + +#pragma region Service Constructor and Destructor + +// +// FUNCTION: CServiceBase::CServiceBase(PWSTR, BOOL, BOOL, BOOL) +// +// PURPOSE: The constructor of CServiceBase. It initializes a new instance +// of the CServiceBase class. The optional parameters (fCanStop, +/// fCanShutdown and fCanPauseContinue) allow you to specify whether the +// service can be stopped, paused and continued, or be notified when system +// shutdown occurs. +// +// PARAMETERS: +// * pszServiceName - the name of the service +// * fCanStop - the service can be stopped +// * fCanShutdown - the service is notified when system shutdown occurs +// * fCanPauseContinue - the service can be paused and continued +// +CServiceBase::CServiceBase( + PWSTR pszServiceName, + BOOL fCanStop, + BOOL fCanShutdown, + BOOL fCanPauseContinue) +{ + // Service name must be a valid string and cannot be NULL. + m_name = (pszServiceName == nullptr) ? L"" : pszServiceName; + + m_statusHandle = nullptr; + + // The service runs in its own process. + m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + + // The service is starting. + m_status.dwCurrentState = SERVICE_START_PENDING; + + // The accepted commands of the service. + DWORD dwControlsAccepted = 0; + if (fCanStop) + dwControlsAccepted |= SERVICE_ACCEPT_STOP; + if (fCanShutdown) + dwControlsAccepted |= SERVICE_ACCEPT_SHUTDOWN; + if (fCanPauseContinue) + dwControlsAccepted |= SERVICE_ACCEPT_PAUSE_CONTINUE; + m_status.dwControlsAccepted = dwControlsAccepted; + + m_status.dwWin32ExitCode = NO_ERROR; + m_status.dwServiceSpecificExitCode = 0; + m_status.dwCheckPoint = 0; + m_status.dwWaitHint = 0; + + NTSTATUS status = EventRegister(&HSA_SERVICE_PROVIDER_GUID, + nullptr, + nullptr, + &m_etwRegHandle); + if (ERROR_SUCCESS != status) + { + wprintf(L"Provider not registered. EventRegister failed with %d\n", status); + } +} + + +// +// FUNCTION: CServiceBase::~CServiceBase() +// +// PURPOSE: The virtual destructor of CServiceBase. +// +CServiceBase::~CServiceBase(void) +{ + if (m_etwRegHandle != NULL) + { + EventUnregister(m_etwRegHandle); + } +} + +#pragma endregion + + +#pragma region Service Start, Stop, Pause, Continue, and Shutdown + +// +// FUNCTION: CServiceBase::Start(DWORD, PWSTR *) +// +// PURPOSE: The function starts the service. It calls the OnStart virtual +// function in which you can specify the actions to take when the service +// starts. If an error occurs during the startup, the error will be logged +// in the Application event log, and the service will be stopped. +// +// PARAMETERS: +// * dwArgc - number of command line arguments +// * lpszArgv - array of command line arguments +// +void CServiceBase::Start(DWORD dwArgc, PWSTR *pszArgv) +{ + WriteEventLogEntry(L"Service trying to start.", TRACE_LEVEL_ERROR); + try + { + // Tell SCM that the service is starting. + SetServiceStatus(SERVICE_START_PENDING); + + // Perform service-specific initialization. + OnStart(dwArgc, pszArgv); + + // Tell SCM that the service is started. + SetServiceStatus(SERVICE_RUNNING); + } + catch (DWORD dwError) + { + // Log the error. + WriteErrorLogEntry(L"Service Start", dwError); + + // Set the service status to be stopped. + SetServiceStatus(SERVICE_STOPPED, dwError); + } + catch (...) + { + // Log the error. + WriteEventLogEntry(L"Service failed to start.", TRACE_LEVEL_ERROR); + + // Set the service status to be stopped. + SetServiceStatus(SERVICE_STOPPED); + } +} + + +// +// FUNCTION: CServiceBase::OnStart(DWORD, PWSTR *) +// +// PURPOSE: When implemented in a derived class, executes when a Start +// command is sent to the service by the SCM or when the operating system +// starts (for a service that starts automatically). Specifies actions to +// take when the service starts. Be sure to periodically call +// CServiceBase::SetServiceStatus() with SERVICE_START_PENDING if the +// procedure is going to take long time. You may also consider spawning a +// new thread in OnStart to perform time-consuming initialization tasks. +// +// PARAMETERS: +// * dwArgc - number of command line arguments +// * lpszArgv - array of command line arguments +// +void CServiceBase::OnStart(DWORD dwArgc, PWSTR *pszArgv) +{ +} + + +// +// FUNCTION: CServiceBase::Stop() +// +// PURPOSE: The function stops the service. It calls the OnStop virtual +// function in which you can specify the actions to take when the service +// stops. If an error occurs, the error will be logged in the Application +// event log, and the service will be restored to the original state. +// +void CServiceBase::Stop() +{ + DWORD dwOriginalState = m_status.dwCurrentState; + try + { + // Tell SCM that the service is stopping. + SetServiceStatus(SERVICE_STOP_PENDING); + + // Perform service-specific stop operations. + OnStop(); + + // Tell SCM that the service is stopped. + SetServiceStatus(SERVICE_STOPPED); + } + catch (DWORD dwError) + { + // Log the error. + WriteErrorLogEntry(L"Service Stop", dwError); + + // Set the orginal service status. + SetServiceStatus(dwOriginalState); + } + catch (...) + { + // Log the error. + WriteEventLogEntry(L"Service failed to stop.", TRACE_LEVEL_ERROR); + + // Set the orginal service status. + SetServiceStatus(dwOriginalState); + } +} + + +// +// FUNCTION: CServiceBase::OnStop() +// +// PURPOSE: When implemented in a derived class, executes when a Stop +// command is sent to the service by the SCM. Specifies actions to take +// when a service stops running. Be sure to periodically call +// CServiceBase::SetServiceStatus() with SERVICE_STOP_PENDING if the +// procedure is going to take long time. +// +void CServiceBase::OnStop() +{ +} + + +// +// FUNCTION: CServiceBase::Pause() +// +// PURPOSE: The function pauses the service if the service supports pause +// and continue. It calls the OnPause virtual function in which you can +// specify the actions to take when the service pauses. If an error occurs, +// the error will be logged in the Application event log, and the service +// will become running. +// +void CServiceBase::Pause() +{ + try + { + // Tell SCM that the service is pausing. + SetServiceStatus(SERVICE_PAUSE_PENDING); + + // Perform service-specific pause operations. + OnPause(); + + // Tell SCM that the service is paused. + SetServiceStatus(SERVICE_PAUSED); + } + catch (DWORD dwError) + { + // Log the error. + WriteErrorLogEntry(L"Service Pause", dwError); + + // Tell SCM that the service is still running. + SetServiceStatus(SERVICE_RUNNING); + } + catch (...) + { + // Log the error. + WriteEventLogEntry(L"Service failed to pause.", TRACE_LEVEL_ERROR); + + // Tell SCM that the service is still running. + SetServiceStatus(SERVICE_RUNNING); + } +} + + +// +// FUNCTION: CServiceBase::OnPause() +// +// PURPOSE: When implemented in a derived class, executes when a Pause +// command is sent to the service by the SCM. Specifies actions to take +// when a service pauses. +// +void CServiceBase::OnPause() +{ +} + + +// +// FUNCTION: CServiceBase::Continue() +// +// PURPOSE: The function resumes normal functioning after being paused if +// the service supports pause and continue. It calls the OnContinue virtual +// function in which you can specify the actions to take when the service +// continues. If an error occurs, the error will be logged in the +// Application event log, and the service will still be paused. +// +void CServiceBase::Continue() +{ + try + { + // Tell SCM that the service is resuming. + SetServiceStatus(SERVICE_CONTINUE_PENDING); + + // Perform service-specific continue operations. + OnContinue(); + + // Tell SCM that the service is running. + SetServiceStatus(SERVICE_RUNNING); + } + catch (DWORD dwError) + { + // Log the error. + WriteErrorLogEntry(L"Service Continue", dwError); + + // Tell SCM that the service is still paused. + SetServiceStatus(SERVICE_PAUSED); + } + catch (...) + { + // Log the error. + WriteEventLogEntry(L"Service failed to resume.", TRACE_LEVEL_ERROR); + + // Tell SCM that the service is still paused. + SetServiceStatus(SERVICE_PAUSED); + } +} + + +// +// FUNCTION: CServiceBase::OnContinue() +// +// PURPOSE: When implemented in a derived class, OnContinue runs when a +// Continue command is sent to the service by the SCM. Specifies actions to +// take when a service resumes normal functioning after being paused. +// +void CServiceBase::OnContinue() +{ +} + + +// +// FUNCTION: CServiceBase::Shutdown() +// +// PURPOSE: The function executes when the system is shutting down. It +// calls the OnShutdown virtual function in which you can specify what +// should occur immediately prior to the system shutting down. If an error +// occurs, the error will be logged in the Application event log. +// +void CServiceBase::Shutdown() +{ + try + { + // Perform service-specific shutdown operations. + OnShutdown(); + + // Tell SCM that the service is stopped. + SetServiceStatus(SERVICE_STOPPED); + } + catch (DWORD dwError) + { + // Log the error. + WriteErrorLogEntry(L"Service Shutdown", dwError); + } + catch (...) + { + // Log the error. + WriteEventLogEntry(L"Service failed to shut down.", TRACE_LEVEL_ERROR); + } +} + + +// +// FUNCTION: CServiceBase::OnShutdown() +// +// PURPOSE: When implemented in a derived class, executes when the system +// is shutting down. Specifies what should occur immediately prior to the +// system shutting down. +// +void CServiceBase::OnShutdown() +{ +} + +#pragma endregion + + +#pragma region Helper Functions + +// +// FUNCTION: CServiceBase::SetServiceStatus(DWORD, DWORD, DWORD) +// +// PURPOSE: The function sets the service status and reports the status to +// the SCM. +// +// PARAMETERS: +// * dwCurrentState - the state of the service +// * dwWin32ExitCode - error code to report +// * dwWaitHint - estimated time for pending operation, in milliseconds +// +void CServiceBase::SetServiceStatus( + _In_ DWORD dwCurrentState, + _In_ DWORD dwWin32ExitCode, + _In_ DWORD dwWaitHint) +{ + static DWORD dwCheckPoint = 1; + + // Fill in the SERVICE_STATUS structure of the service. + + m_status.dwCurrentState = dwCurrentState; + m_status.dwWin32ExitCode = dwWin32ExitCode; + m_status.dwWaitHint = dwWaitHint; + + m_status.dwCheckPoint = + ((dwCurrentState == SERVICE_RUNNING) || + (dwCurrentState == SERVICE_STOPPED)) ? + 0 : dwCheckPoint++; + + // Report the status of the service to the SCM. + ::SetServiceStatus(m_statusHandle, &m_status); +} + + +// +// FUNCTION: CServiceBase::WriteEventLogEntry(PWSTR, WORD) +// +// PURPOSE: Log an event. +// +// PARAMETERS: +// * pszMessage - string message to be logged. +// * wType - the type of event to be logged. The parameter can be one of +// the following values. +// +// EVENTLOG_SUCCESS +// EVENTLOG_AUDIT_FAILURE +// EVENTLOG_AUDIT_SUCCESS +// EVENTLOG_ERROR_TYPE +// EVENTLOG_INFORMATION_TYPE +// EVENTLOG_WARNING_TYPE +// +void CServiceBase::WriteEventLogEntry( + _In_ PWSTR pszMessage, + _In_ BYTE bLevel) +{ + if (m_etwRegHandle != NULL) + { + EventWriteString(m_etwRegHandle, bLevel, 0, pszMessage); + } +} + +// +// FUNCTION: CServiceBase::WriteErrorLogEntry(PWSTR, DWORD) +// +// PURPOSE: Log an event. +// +// PARAMETERS: +// * pszFunction - the function that gives the error +// * dwError - the error code +// +void CServiceBase::WriteErrorLogEntry( + _In_ PWSTR pszFunction, + _In_ DWORD dwError) +{ + wchar_t szMessage[260]; + StringCchPrintf(szMessage, ARRAYSIZE(szMessage), + L"%s failed w/err 0x%08lx", pszFunction, dwError); + WriteEventLogEntry(szMessage, TRACE_LEVEL_ERROR); +} + +#pragma endregion
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceBase.h b/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceBase.h new file mode 100644 index 00000000..ebae808e --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceBase.h @@ -0,0 +1,121 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +// Provides a base class for a service that will exist as part of a service +// application. CServiceBase must be derived from when creating a new service +// class. + +#pragma once + +#include <windows.h> +#include <evntprov.h> + +class CServiceBase +{ +public: + + // Register the executable for a service with the Service Control Manager + // (SCM). After you call Run(ServiceBase), the SCM issues a Start command, + // which results in a call to the OnStart method in the service. This + // method blocks until the service has stopped. + static BOOL Run(CServiceBase& service); + + // Service object constructor. The optional parameters (fCanStop, + // fCanShutdown and fCanPauseContinue) allow you to specify whether the + // service can be stopped, paused and continued, or be notified when + // system shutdown occurs. + CServiceBase(PWSTR pszServiceName, + BOOL fCanStop = TRUE, + BOOL fCanShutdown = TRUE, + BOOL fCanPauseContinue = FALSE); + + // Service object destructor. + virtual ~CServiceBase(void); + + // Stop the service. + void Stop(); + +protected: + + // When implemented in a derived class, executes when a Start command is + // sent to the service by the SCM or when the operating system starts + // (for a service that starts automatically). Specifies actions to take + // when the service starts. + virtual void OnStart(DWORD dwArgc, PWSTR *pszArgv); + + // When implemented in a derived class, executes when a Stop command is + // sent to the service by the SCM. Specifies actions to take when a + // service stops running. + virtual void OnStop(); + + // When implemented in a derived class, executes when a Pause command is + // sent to the service by the SCM. Specifies actions to take when a + // service pauses. + virtual void OnPause(); + + // When implemented in a derived class, OnContinue runs when a Continue + // command is sent to the service by the SCM. Specifies actions to take + // when a service resumes normal functioning after being paused. + virtual void OnContinue(); + + // When implemented in a derived class, executes when the system is + // shutting down. Specifies what should occur immediately prior to the + // system shutting down. + virtual void OnShutdown(); + + // Set the service status and report the status to the SCM. + void SetServiceStatus(DWORD dwCurrentState, + DWORD dwWin32ExitCode = NO_ERROR, + DWORD dwWaitHint = 0); + + // Log an event. + virtual void WriteEventLogEntry(PWSTR pszMessage, BYTE bLevel); + + // Log an event. + void WriteErrorLogEntry(PWSTR pszFunction, + DWORD dwError = GetLastError()); + +private: + + // Entry point for the service. It registers the handler function for the + // service and starts the service. + static void WINAPI ServiceMain(DWORD dwArgc, LPWSTR *lpszArgv); + + // The function is called by the SCM whenever a control code is sent to + // the service. + static void WINAPI ServiceCtrlHandler(DWORD dwCtrl); + + // Start the service. + void Start(DWORD dwArgc, PWSTR *pszArgv); + + // Pause the service. + void Pause(); + + // Resume the service after being paused. + void Continue(); + + // Execute when the system is shutting down. + void Shutdown(); + + // The singleton service instance. + static CServiceBase *s_service; + + // The name of the service + PWSTR m_name; + + // The status of the service + SERVICE_STATUS m_status; + + // The service status handle + SERVICE_STATUS_HANDLE m_statusHandle; + + REGHANDLE m_etwRegHandle; +};
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceInstaller.cpp b/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceInstaller.cpp new file mode 100644 index 00000000..27b107a9 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceInstaller.cpp @@ -0,0 +1,191 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "stdafx.h" +#pragma region "Includes" + +#include <stdio.h> +#include <windows.h> +#include "ServiceInstaller.h" +#pragma endregion + + +// +// FUNCTION: InstallService +// +// PURPOSE: Install the current application as a service to the local +// service control manager database. +// +// PARAMETERS: +// * pszServiceName - the name of the service to be installed +// * pszDisplayName - the display name of the service +// * dwStartType - the service start option. This parameter can be one of +// the following values: SERVICE_AUTO_START, SERVICE_BOOT_START, +// SERVICE_DEMAND_START, SERVICE_DISABLED, SERVICE_SYSTEM_START. +// * pszDependencies - a pointer to a double null-terminated array of null- +// separated names of services or load ordering groups that the system +// must start before this service. +// * pszAccount - the name of the account under which the service runs. +// * pszPassword - the password to the account name. +// +// NOTE: If the function fails to install the service, it prints the error +// in the standard output stream for users to diagnose the problem. +// +void InstallService( + _In_ PWSTR pszServiceName, + _In_ PWSTR pszDisplayName, + _In_ DWORD dwStartType, + _In_ PWSTR pszDependencies, + _In_ PWSTR pszAccount, + _In_ PWSTR pszPassword) +{ + wchar_t szPath[MAX_PATH]; + SC_HANDLE schSCManager = nullptr; + SC_HANDLE schService = nullptr; + + if (GetModuleFileName(nullptr, szPath, ARRAYSIZE(szPath)) == 0) + { + wprintf(L"GetModuleFileName failed w/err 0x%08lx\n", GetLastError()); + goto Cleanup; + } + + // Open the local default service control manager database + schSCManager = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT | + SC_MANAGER_CREATE_SERVICE); + if (schSCManager == nullptr) + { + wprintf(L"OpenSCManager failed w/err 0x%08lx\n", GetLastError()); + goto Cleanup; + } + + // Install the service into SCM by calling CreateService + schService = CreateService( + schSCManager, // SCManager database + pszServiceName, // Name of service + pszDisplayName, // Name to display + SERVICE_QUERY_STATUS, // Desired access + SERVICE_WIN32_OWN_PROCESS, // Service type + dwStartType, // Service start type + SERVICE_ERROR_NORMAL, // Error control type + szPath, // Service's binary + nullptr, // No load ordering group + nullptr, // No tag identifier + pszDependencies, // Dependencies + pszAccount, // Service running account + pszPassword // Password of the account + ); + + if (schService == nullptr) + { + wprintf(L"CreateService failed w/err 0x%08lx\n", GetLastError()); + goto Cleanup; + } + + wprintf(L"%s is installed.\n", pszServiceName); + +Cleanup: + // Centralized cleanup for all allocated resources. + if (schSCManager) + { + CloseServiceHandle(schSCManager); + schSCManager = nullptr; + } + if (schService) + { + CloseServiceHandle(schService); + schService = nullptr; + } +} + + +// +// FUNCTION: UninstallService +// +// PURPOSE: Stop and remove the service from the local service control +// manager database. +// +// PARAMETERS: +// * pszServiceName - the name of the service to be removed. +// +// NOTE: If the function fails to uninstall the service, it prints the +// error in the standard output stream for users to diagnose the problem. +// +void UninstallService(_In_ PWSTR pszServiceName) +{ + SC_HANDLE schSCManager = nullptr; + SC_HANDLE schService = nullptr; + SERVICE_STATUS ssSvcStatus = {}; + + // Open the local default service control manager database + schSCManager = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT); + if (schSCManager == nullptr) + { + wprintf(L"OpenSCManager failed w/err 0x%08lx\n", GetLastError()); + goto Cleanup; + } + + // Open the service with delete, stop, and query status permissions + schService = OpenService(schSCManager, pszServiceName, SERVICE_STOP | + SERVICE_QUERY_STATUS | DELETE); + if (schService == nullptr) + { + wprintf(L"OpenService failed w/err 0x%08lx\n", GetLastError()); + goto Cleanup; + } + + // Try to stop the service + if (ControlService(schService, SERVICE_CONTROL_STOP, &ssSvcStatus)) + { + wprintf(L"Stopping %s.", pszServiceName); + Sleep(1000); + + while (QueryServiceStatus(schService, &ssSvcStatus)) + { + if (ssSvcStatus.dwCurrentState == SERVICE_STOP_PENDING) + { + wprintf(L"."); + Sleep(1000); + } + else break; + } + + if (ssSvcStatus.dwCurrentState == SERVICE_STOPPED) + { + wprintf(L"\n%s is stopped.\n", pszServiceName); + } + else + { + wprintf(L"\n%s failed to stop.\n", pszServiceName); + } + } + + // Now remove the service by calling DeleteService. + if (!DeleteService(schService)) + { + wprintf(L"DeleteService failed w/err 0x%08lx\n", GetLastError()); + goto Cleanup; + } + + wprintf(L"%s is removed.\n", pszServiceName); + +Cleanup: + // Centralized cleanup for all allocated resources. + if (schSCManager) + { + CloseServiceHandle(schSCManager); + schSCManager = nullptr; + } + if (schService) + { + CloseServiceHandle(schService); + schService = nullptr; + } +}
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceInstaller.h b/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceInstaller.h new file mode 100644 index 00000000..af6507e6 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/ServiceInstaller.h @@ -0,0 +1,57 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +// The file declares functions that install and uninstall the service. + +#pragma once + +// +// FUNCTION: InstallService +// +// PURPOSE: Install the current application as a service to the local +// service control manager database. +// +// PARAMETERS: +// * pszServiceName - the name of the service to be installed +// * pszDisplayName - the display name of the service +// * dwStartType - the service start option. This parameter can be one of +// the following values: SERVICE_AUTO_START, SERVICE_BOOT_START, +// SERVICE_DEMAND_START, SERVICE_DISABLED, SERVICE_SYSTEM_START. +// * pszDependencies - a pointer to a double null-terminated array of null- +// separated names of services or load ordering groups that the system +// must start before this service. +// * pszAccount - the name of the account under which the service runs. +// * pszPassword - the password to the account name. +// +// NOTE: If the function fails to install the service, it prints the error +// in the standard output stream for users to diagnose the problem. +// +void InstallService(PWSTR pszServiceName, + PWSTR pszDisplayName, + DWORD dwStartType, + PWSTR pszDependencies, + PWSTR pszAccount, + PWSTR pszPassword); + + +// +// FUNCTION: UninstallService +// +// PURPOSE: Stop and remove the service from the local service control +// manager database. +// +// PARAMETERS: +// * pszServiceName - the name of the service to be removed. +// +// NOTE: If the function fails to uninstall the service, it prints the +// error in the standard output stream for users to diagnose the problem. +// +void UninstallService(PWSTR pszServiceName); diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/stdafx.cpp b/general/WinHEC 2017 Lab/Toaster Driver/Service/stdafx.cpp new file mode 100644 index 00000000..ce19a949 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// RpcServer.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/stdafx.h b/general/WinHEC 2017 Lab/Toaster Driver/Service/stdafx.h new file mode 100644 index 00000000..306c4330 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/stdafx.h @@ -0,0 +1,15 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#include <stdio.h> +#include <tchar.h> + +#define NOMINMAX // disable min and max macros in windows.h + +extern bool ShutdownRequested; diff --git a/general/WinHEC 2017 Lab/Toaster Driver/Service/targetver.h b/general/WinHEC 2017 Lab/Toaster Driver/Service/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/Service/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include <SDKDDKVer.h> diff --git a/general/WinHEC 2017 Lab/Toaster Driver/toaster.sln b/general/WinHEC 2017 Lab/Toaster Driver/toaster.sln new file mode 100644 index 00000000..35e5dcbc --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/toaster.sln @@ -0,0 +1,40 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.12 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "toaster", "toaster\toaster.vcxproj", "{2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|ARM = Release|ARM + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Debug|ARM.ActiveCfg = Debug|ARM + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Debug|ARM.Build.0 = Debug|ARM + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Debug|ARM64.Build.0 = Debug|ARM64 + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Debug|x64.ActiveCfg = Debug|x64 + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Debug|x64.Build.0 = Debug|x64 + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Debug|x86.ActiveCfg = Debug|Win32 + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Debug|x86.Build.0 = Debug|Win32 + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Release|ARM.ActiveCfg = Release|ARM + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Release|ARM.Build.0 = Release|ARM + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Release|ARM64.ActiveCfg = Release|ARM64 + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Release|ARM64.Build.0 = Release|ARM64 + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Release|x64.ActiveCfg = Release|x64 + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Release|x64.Build.0 = Release|x64 + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Release|x86.ActiveCfg = Release|Win32 + {2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/general/WinHEC 2017 Lab/Toaster Driver/toaster/driver.h b/general/WinHEC 2017 Lab/Toaster Driver/toaster/driver.h new file mode 100644 index 00000000..8e7ade01 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/toaster/driver.h @@ -0,0 +1,80 @@ +/*++ +Copyright (c) 1990-2000 Microsoft Corporation All Rights Reserved + +Module Name: + + driver.h + +Abstract: + + This module contains the common declarations for the + bus, function and filter drivers. + +Environment: + + kernel mode only + +--*/ + +//#include "public.h" + +// +// Define an Interface Guid to access the proprietary toaster interface. +// This guid is used to identify a specific interface in IRP_MN_QUERY_INTERFACE +// handler. +// + +DEFINE_GUID(GUID_TOASTER_INTERFACE_STANDARD, + 0xe0b27630, 0x5434, 0x11d3, 0xb8, 0x90, 0x0, 0xc0, 0x4f, 0xad, 0x51, 0x71); +// {E0B27630-5434-11d3-B890-00C04FAD5171} + + +// +// GUID definition are required to be outside of header inclusion pragma to avoid +// error during precompiled headers. +// + +#ifndef __DRIVER_H +#define __DRIVER_H + +// +// Define Interface reference/dereference routines for +// Interfaces exported by IRP_MN_QUERY_INTERFACE +// + +typedef VOID (*PINTERFACE_REFERENCE)(PVOID Context); +typedef VOID (*PINTERFACE_DEREFERENCE)(PVOID Context); + +typedef +BOOLEAN +(*PTOASTER_GET_CRISPINESS_LEVEL)( + IN PVOID Context, + OUT PUCHAR Level + ); + +typedef +BOOLEAN +(*PTOASTER_SET_CRISPINESS_LEVEL)( + IN PVOID Context, + OUT UCHAR Level + ); + +typedef +BOOLEAN +(*PTOASTER_IS_CHILD_PROTECTED)( + IN PVOID Context + ); + +// +// Interface for getting and setting power level etc., +// +typedef struct _TOASTER_INTERFACE_STANDARD { + INTERFACE InterfaceHeader; + PTOASTER_GET_CRISPINESS_LEVEL GetCrispinessLevel; + PTOASTER_SET_CRISPINESS_LEVEL SetCrispinessLevel; + PTOASTER_IS_CHILD_PROTECTED IsSafetyLockEnabled; //): +} TOASTER_INTERFACE_STANDARD, *PTOASTER_INTERFACE_STANDARD; + + +#endif + diff --git a/general/WinHEC 2017 Lab/Toaster Driver/toaster/public.h b/general/WinHEC 2017 Lab/Toaster Driver/toaster/public.h new file mode 100644 index 00000000..0628f95f --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/toaster/public.h @@ -0,0 +1,167 @@ +/*++ +Copyright (c) 1990-2000 Microsoft Corporation All Rights Reserved + +Module Name: + + public.h + +Abstract: + + This module contains the common declarations shared by driver + and user applications. + +Environment: + + user and kernel + +--*/ + +// +// Define an Interface Guid for bus enumerator class. +// This GUID is used to register (IoRegisterDeviceInterface) +// an instance of an interface so that enumerator application +// can send an ioctl to the bus driver. +// + +DEFINE_GUID (GUID_DEVINTERFACE_BUSENUM_TOASTER, + 0xD35F7840, 0x6A0C, 0x11d2, 0xB8, 0x41, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x71); +// {D35F7840-6A0C-11d2-B841-00C04FAD5171} + +// +// Define an Interface Guid for toaster device class. +// This GUID is used to register (IoRegisterDeviceInterface) +// an instance of an interface so that user application +// can control the toaster device. +// + +DEFINE_GUID (GUID_DEVINTERFACE_TOASTER, + 0x781EF630, 0x72B2, 0x11d2, 0xB8, 0x52, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x71); +//{781EF630-72B2-11d2-B852-00C04FAD5171} + +// +// Define a Setup Class GUID for Toaster Class. This is same +// as the TOASTSER CLASS guid in the INF files. +// + +DEFINE_GUID (GUID_DEVCLASS_TOASTER, + 0xB85B7C50, 0x6A01, 0x11d2, 0xB8, 0x41, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x71); +//{B85B7C50-6A01-11d2-B841-00C04FAD5171} + +// +// Define a WMI GUID to get busenum info. +// + +DEFINE_GUID (TOASTER_BUS_WMI_STD_DATA_GUID, + 0x0006A660, 0x8F12, 0x11d2, 0xB8, 0x54, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x71); +//{0006A660-8F12-11d2-B854-00C04FAD5171} + +// +// Define a WMI GUID to get toaster device info. +// + +DEFINE_GUID (TOASTER_WMI_STD_DATA_GUID, + 0xBBA21300L, 0x6DD3, 0x11d2, 0xB8, 0x44, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x71); + +// +// Define a WMI GUID to represent device arrival notification WMIEvent class. +// + +DEFINE_GUID (TOASTER_NOTIFY_DEVICE_ARRIVAL_EVENT, + 0x1cdaff1, 0xc901, 0x45b4, 0xb3, 0x59, 0xb5, 0x54, 0x27, 0x25, 0xe2, 0x9c); +// {01CDAFF1-C901-45b4-B359-B5542725E29C} + + +// +// GUID definition are required to be outside of header inclusion pragma to avoid +// error during precompiled headers. +// + +#ifndef __PUBLIC_H +#define __PUBLIC_H + +#define BUS_HARDWARE_IDS L"{B85B7C50-6A01-11d2-B841-00C04FAD5171}\\MsToaster\0" +#define BUS_HARDWARE_IDS_LENGTH sizeof (BUS_HARDWARE_IDS) + +#define BUSENUM_COMPATIBLE_IDS L"{B85B7C50-6A01-11d2-B841-00C04FAD5171}\\MsCompatibleToaster\0" +#define BUSENUM_COMPATIBLE_IDS_LENGTH sizeof(BUSENUM_COMPATIBLE_IDS) + + +#define FILE_DEVICE_BUSENUM FILE_DEVICE_BUS_EXTENDER + +#define BUSENUM_IOCTL(_index_) \ + CTL_CODE (FILE_DEVICE_BUSENUM, _index_, METHOD_BUFFERED, FILE_READ_DATA) + +#define IOCTL_BUSENUM_PLUGIN_HARDWARE BUSENUM_IOCTL (0x0) +#define IOCTL_BUSENUM_UNPLUG_HARDWARE BUSENUM_IOCTL (0x1) +#define IOCTL_BUSENUM_EJECT_HARDWARE BUSENUM_IOCTL (0x2) +#define IOCTL_TOASTER_DONT_DISPLAY_IN_UI_DEVICE BUSENUM_IOCTL (0x3) + +// +// Data structure used in PlugIn and UnPlug ioctls +// + +typedef struct _BUSENUM_PLUGIN_HARDWARE +{ + // + // sizeof (struct _BUSENUM_HARDWARE) + // + IN ULONG Size; + + // + // Unique serial number of the device to be enumerated. + // Enumeration will be failed if another device on the + // bus has the same serail number. + // + + IN ULONG SerialNo; + + // + // An array of (zero terminated wide character strings). The array itself + // also null terminated (ie, MULTI_SZ) + // + #pragma warning(disable:4200) // nonstandard extension used + + IN WCHAR HardwareIDs[]; + + #pragma warning(default:4200) + +} BUSENUM_PLUGIN_HARDWARE, *PBUSENUM_PLUGIN_HARDWARE; + +typedef struct _BUSENUM_UNPLUG_HARDWARE +{ + // + // sizeof (struct _REMOVE_HARDWARE) + // + + IN ULONG Size; + + // + // Serial number of the device to be plugged out + // + + ULONG SerialNo; + + ULONG Reserved[2]; + +} BUSENUM_UNPLUG_HARDWARE, *PBUSENUM_UNPLUG_HARDWARE; + +typedef struct _BUSENUM_EJECT_HARDWARE +{ + // + // sizeof (struct _EJECT_HARDWARE) + // + + IN ULONG Size; + + // + // Serial number of the device to be ejected + // + + ULONG SerialNo; + + ULONG Reserved[2]; + +} BUSENUM_EJECT_HARDWARE, *PBUSENUM_EJECT_HARDWARE; + +#endif + diff --git a/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.c b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.c new file mode 100644 index 00000000..6ed215db --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.c @@ -0,0 +1,418 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + + THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR + PURPOSE. + +Module Name: + + Toaster.c + +Abstract: + + This is a simple form of function driver for toaster device. The driver + doesn't handle any PnP and Power events because the framework provides + default behavior for those events. This driver has enough support to + allow an user application (toast/notify.exe) to open the device + interface registered by the driver and send read, write or ioctl requests. + +Environment: + + Kernel mode + +--*/ + +#include "toaster.h" + +#ifdef ALLOC_PRAGMA +#pragma alloc_text (INIT, DriverEntry) +#pragma alloc_text (PAGE, ToasterEvtDeviceAdd) +#pragma alloc_text (PAGE, ToasterEvtIoRead) +#pragma alloc_text (PAGE, ToasterEvtIoWrite) +#pragma alloc_text (PAGE, ToasterEvtIoDeviceControl) +#endif + + +NTSTATUS +DriverEntry( + IN PDRIVER_OBJECT DriverObject, + IN PUNICODE_STRING RegistryPath + ) +/*++ + +Routine Description: + DriverEntry initializes the driver and is the first routine called by the + system after the driver is loaded. DriverEntry configures and creates a WDF driver + object. + . +Parameters Description: + + DriverObject - represents the instance of the function driver that is loaded + into memory. DriverObject is allocated by the system before the + driver is loaded, and it is released by the system after the system unloads + the function driver from memory. + + RegistryPath - represents the driver specific path in the Registry. + The function driver can use the path to store driver related data between + reboots. The path does not store hardware instance specific data. + +Return Value: + + STATUS_SUCCESS if successful, + STATUS_UNSUCCESSFUL otherwise. + +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + WDF_DRIVER_CONFIG config; + + KdPrint(("Toaster Function Driver Sample - Driver Framework Edition.\n")); + + // + // Initiialize driver config to control the attributes that + // are global to the driver. Note that framework by default + // provides a driver unload routine. If DriverEntry creates any resources + // that require clean-up in driver unload, + // you can manually override the default by supplying a pointer to the EvtDriverUnload + // callback in the config structure. In general xxx_CONFIG_INIT macros are provided to + // initialize most commonly used members. + // + + WDF_DRIVER_CONFIG_INIT( + &config, + ToasterEvtDeviceAdd + ); + + + // + // Create a framework driver object to represent our driver. + // + status = WdfDriverCreate( + DriverObject, + RegistryPath, + WDF_NO_OBJECT_ATTRIBUTES, // Driver Attributes + &config, // Driver Config Info + WDF_NO_HANDLE + ); + + if (!NT_SUCCESS(status)) { + KdPrint( ("WdfDriverCreate failed with status 0x%x\n", status)); + } + + return status; +} + + +NTSTATUS +ToasterEvtDeviceAdd( + IN WDFDRIVER Driver, + IN PWDFDEVICE_INIT DeviceInit + ) +/*++ +Routine Description: + + ToasterEvtDeviceAdd is called by the framework in response to AddDevice + call from the PnP manager. We create and initialize a WDF device object to + represent a new instance of toaster device. + +Arguments: + + Driver - Handle to a framework driver object created in DriverEntry + + DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure. + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + PFDO_DATA fdoData; + WDF_IO_QUEUE_CONFIG queueConfig; + WDF_OBJECT_ATTRIBUTES fdoAttributes; + WDFDEVICE hDevice; + WDFQUEUE queue; + + UNREFERENCED_PARAMETER(Driver); + + PAGED_CODE(); + + KdPrint(("ToasterEvtDeviceAdd called\n")); + + // + // Initialize attributes and a context area for the device object. + // + // + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&fdoAttributes, FDO_DATA); + + // + // Create a framework device object.This call will in turn create + // a WDM device object, attach to the lower stack, and set the + // appropriate flags and attributes. + // + status = WdfDeviceCreate(&DeviceInit, &fdoAttributes, &hDevice); + if (!NT_SUCCESS(status)) { + KdPrint( ("WdfDeviceCreate failed with status code 0x%x\n", status)); + return status; + } + + // + // Get the device context by using the accessor function specified in + // the WDF_DECLARE_CONTEXT_TYPE_WITH_NAME macro for FDO_DATA. + // + fdoData = ToasterFdoGetData(hDevice); + + // + // Tell the Framework that this device will need an interface + // + status = WdfDeviceCreateDeviceInterface( + hDevice, + (LPGUID) &GUID_DEVINTERFACE_TOASTER, + NULL // ReferenceString + ); + + if (!NT_SUCCESS (status)) { + KdPrint( ("WdfDeviceCreateDeviceInterface failed 0x%x\n", status)); + return status; + } + + // + // Register I/O callbacks to tell the framework that you are interested + // in handling IRP_MJ_READ, IRP_MJ_WRITE, and IRP_MJ_DEVICE_CONTROL requests. + // If a specific callback function is not specified for one ofthese, + // the request will be dispatched to the EvtIoDefault handler, if any. + // If there is no EvtIoDefault handler, the request will be failed with + // STATUS_INVALID_DEVICE_REQUEST. + // WdfIoQueueDispatchParallel means that we are capable of handling + // all the I/O requests simultaneously and we are responsible for protecting + // data that could be accessed by these callbacks simultaneously. + // A default queue gets all the requests that are not + // configured for forwarding using WdfDeviceConfigureRequestDispatching. + // + WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&queueConfig, WdfIoQueueDispatchParallel); + + queueConfig.EvtIoRead = ToasterEvtIoRead; + queueConfig.EvtIoWrite = ToasterEvtIoWrite; + queueConfig.EvtIoDeviceControl = ToasterEvtIoDeviceControl; + + // + // By default, Static Driver Verifier (SDV) displays a warning if it + // doesn't find the EvtIoStop callback on a power-managed queue. + // The 'assume' below causes SDV to suppress this warning. If the driver + // has not explicitly set PowerManaged to WdfFalse, the framework creates + // power-managed queues when the device is not a filter driver. Normally + // the EvtIoStop is required for power-managed queues, but for this driver + // it is not needed b/c the driver doesn't hold on to the requests or + // forward them to other drivers. This driver completes the requests + // directly in the queue's handlers. If the EvtIoStop callback is not + // implemented, the framework waits for all driver-owned requests to be + // done before moving in the Dx/sleep states or before removing the + // device, which is the correct behavior for this type of driver. + // If the requests were taking an indeterminate amount of time to complete, + // or if the driver forwarded the requests to a lower driver/another stack, + // the queue should have an EvtIoStop/EvtIoResume. + // + __analysis_assume(queueConfig.EvtIoStop != 0); + status = WdfIoQueueCreate( + hDevice, + &queueConfig, + WDF_NO_OBJECT_ATTRIBUTES, + &queue + ); + __analysis_assume(queueConfig.EvtIoStop == 0); + + if (!NT_SUCCESS (status)) { + + KdPrint( ("WdfIoQueueCreate failed 0x%x\n", status)); + return status; + } + + return status; +} + +VOID +ToasterEvtIoRead ( + WDFQUEUE Queue, + WDFREQUEST Request, + size_t Length + ) +/*++ + +Routine Description: + + Performs read from the toaster device. This event is called when the + framework receives IRP_MJ_READ requests. + +Arguments: + + Queue - Handle to the framework queue object that is associated with the + I/O request. + Request - Handle to a framework request object. + + Lenght - Length of the data buffer associated with the request. + By default, the queue does not dispatch + zero length read & write requests to the driver and instead to + complete such requests with status success. So we will never get + a zero length request. + +Return Value: + + None. + +--*/ +{ + NTSTATUS status; + ULONG_PTR bytesCopied =0; + WDFMEMORY memory; + + UNREFERENCED_PARAMETER(Queue); + UNREFERENCED_PARAMETER(Length); + + PAGED_CODE(); + + KdPrint(( "ToasterEvtIoRead: Request: 0x%p, Queue: 0x%p\n", + Request, Queue)); + + // + // Get the request memory and perform read operation here + // + status = WdfRequestRetrieveOutputMemory(Request, &memory); + if(NT_SUCCESS(status) ) { + // + // Copy data into the memory buffer using WdfMemoryCopyFromBuffer + // + } + + WdfRequestCompleteWithInformation(Request, status, bytesCopied); +} + +VOID +ToasterEvtIoWrite ( + WDFQUEUE Queue, + WDFREQUEST Request, + size_t Length + ) +/*++ + +Routine Description: + + Performs write to the toaster device. This event is called when the + framework receives IRP_MJ_WRITE requests. + +Arguments: + + Queue - Handle to the framework queue object that is associated with the + I/O request. + Request - Handle to a framework request object. + + Lenght - Length of the data buffer associated with the request. + The default property of the queue is to not dispatch + zero lenght read & write requests to the driver and + complete is with status success. So we will never get + a zero length request. + +Return Value: + + None +--*/ + +{ + NTSTATUS status; + ULONG_PTR bytesWritten =0; + WDFMEMORY memory; + + UNREFERENCED_PARAMETER(Queue); + UNREFERENCED_PARAMETER(Length); + + KdPrint(("ToasterEvtIoWrite. Request: 0x%p, Queue: 0x%p\n", + Request, Queue)); + + PAGED_CODE(); + + // + // Get the request buffer and perform write operation here + // + status = WdfRequestRetrieveInputMemory(Request, &memory); + if(NT_SUCCESS(status) ) { + // + // 1) Use WdfMemoryCopyToBuffer to copy data from the request + // to driver buffer. + // 2) Or get the buffer pointer from the request by calling + // WdfRequestRetrieveInputBuffer + // 3) Or you can get the buffer pointer from the memory handle + // by calling WdfMemoryGetBuffer. + // + bytesWritten = Length; + } + + WdfRequestCompleteWithInformation(Request, status, bytesWritten); + +} + + +VOID +ToasterEvtIoDeviceControl( + IN WDFQUEUE Queue, + IN WDFREQUEST Request, + IN size_t OutputBufferLength, + IN size_t InputBufferLength, + IN ULONG IoControlCode + ) +/*++ +Routine Description: + + This event is called when the framework receives IRP_MJ_DEVICE_CONTROL + requests from the system. + +Arguments: + + Queue - Handle to the framework queue object that is associated + with the I/O request. + Request - Handle to a framework request object. + + OutputBufferLength - length of the request's output buffer, + if an output buffer is available. + InputBufferLength - length of the request's input buffer, + if an input buffer is available. + + IoControlCode - the driver-defined or system-defined I/O control code + (IOCTL) that is associated with the request. + +Return Value: + + VOID + +--*/ +{ + NTSTATUS status= STATUS_SUCCESS; + + UNREFERENCED_PARAMETER(Queue); + UNREFERENCED_PARAMETER(OutputBufferLength); + UNREFERENCED_PARAMETER(InputBufferLength); + + KdPrint(("ToasterEvtIoDeviceControl called\n")); + + PAGED_CODE(); + + // + // Use WdfRequestRetrieveInputBuffer and WdfRequestRetrieveOutputBuffer + // to get the request buffers. + // + + switch (IoControlCode) { + + default: + status = STATUS_INVALID_DEVICE_REQUEST; + } + + // + // Complete the Request. + // + WdfRequestCompleteWithInformation(Request, status, (ULONG_PTR) 0); +} + + diff --git a/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.h b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.h new file mode 100644 index 00000000..fc847d2d --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.h @@ -0,0 +1,134 @@ +/*++ + +Copyright (c) 1990-2000 Microsoft Corporation All Rights Reserved + +Module Name: + + Toaster.h + +Abstract: + + Header file for the toaster driver modules. + +Environment: + + Kernel mode + +--*/ + + +#if !defined(_TOASTER_H_) +#define _TOASTER_H_ + +#include <ntddk.h> +#include <wdf.h> + +#define NTSTRSAFE_LIB +#include <ntstrsafe.h> + +#include "wmilib.h" +#include <initguid.h> +#include "driver.h" +#include "public.h" + +// For Featured driver only +#ifdef TOASTER_FUNC_FEATURED +#include <wpprecorder.h> +#endif // TOASTER_FUNC_FEATURED + +#define TOASTER_POOL_TAG (ULONG) 'saoT' + +#define MOFRESOURCENAME L"ToasterWMI" + +#define TOASTER_FUNC_DEVICE_LOG_ID "ToasterDevice" +// +// The device extension for the device object +// +typedef struct _FDO_DATA +{ + + WDFWMIINSTANCE WmiDeviceArrivalEvent; + + BOOLEAN WmiPowerDeviceEnableRegistered; + + TOASTER_INTERFACE_STANDARD BusInterface; + +// For Featured driver only +#ifdef TOASTER_FUNC_FEATURED + RECORDER_LOG WppRecorderLog; +#endif // TOASTER_FUNC_FEATURED + +} FDO_DATA, *PFDO_DATA; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(FDO_DATA, ToasterFdoGetData) + + +// +// Connector Types +// + +#define TOASTER_WMI_STD_I8042 0 +#define TOASTER_WMI_STD_SERIAL 1 +#define TOASTER_WMI_STD_PARALEL 2 +#define TOASTER_WMI_STD_USB 3 + +DRIVER_INITIALIZE DriverEntry; +EVT_WDF_DRIVER_UNLOAD ToasterEvtDriverUnload; + +EVT_WDF_DRIVER_DEVICE_ADD ToasterEvtDeviceAdd; + +EVT_WDF_DEVICE_CONTEXT_CLEANUP ToasterEvtDeviceContextCleanup; +EVT_WDF_DEVICE_D0_ENTRY ToasterEvtDeviceD0Entry; +EVT_WDF_DEVICE_D0_EXIT ToasterEvtDeviceD0Exit; +EVT_WDF_DEVICE_PREPARE_HARDWARE ToasterEvtDevicePrepareHardware; +EVT_WDF_DEVICE_RELEASE_HARDWARE ToasterEvtDeviceReleaseHardware; + +EVT_WDF_DEVICE_SELF_MANAGED_IO_INIT ToasterEvtDeviceSelfManagedIoInit; + +// +// Io events callbacks. +// +EVT_WDF_IO_QUEUE_IO_READ ToasterEvtIoRead; +EVT_WDF_IO_QUEUE_IO_WRITE ToasterEvtIoWrite; +EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL ToasterEvtIoDeviceControl; +EVT_WDF_DEVICE_FILE_CREATE ToasterEvtDeviceFileCreate; +EVT_WDF_FILE_CLOSE ToasterEvtFileClose; + +NTSTATUS +ToasterWmiRegistration( + _In_ WDFDEVICE Device + ); + +// +// Power events callbacks +// +EVT_WDF_DEVICE_ARM_WAKE_FROM_S0 ToasterEvtDeviceArmWakeFromS0; +EVT_WDF_DEVICE_ARM_WAKE_FROM_SX ToasterEvtDeviceArmWakeFromSx; +EVT_WDF_DEVICE_DISARM_WAKE_FROM_S0 ToasterEvtDeviceDisarmWakeFromS0; +EVT_WDF_DEVICE_DISARM_WAKE_FROM_SX ToasterEvtDeviceDisarmWakeFromSx; +EVT_WDF_DEVICE_WAKE_FROM_S0_TRIGGERED ToasterEvtDeviceWakeFromS0Triggered; +EVT_WDF_DEVICE_WAKE_FROM_SX_TRIGGERED ToasterEvtDeviceWakeFromSxTriggered; + +PCHAR +DbgDevicePowerString( + IN WDF_POWER_DEVICE_STATE Type + ); + +// +// WMI event callbacks +// +EVT_WDF_WMI_INSTANCE_QUERY_INSTANCE EvtWmiInstanceStdDeviceDataQueryInstance; +EVT_WDF_WMI_INSTANCE_QUERY_INSTANCE EvtWmiInstanceToasterControlQueryInstance; +EVT_WDF_WMI_INSTANCE_SET_INSTANCE EvtWmiInstanceStdDeviceDataSetInstance; +EVT_WDF_WMI_INSTANCE_SET_INSTANCE EvtWmiInstanceToasterControlSetInstance; +EVT_WDF_WMI_INSTANCE_SET_ITEM EvtWmiInstanceToasterControlSetItem; +EVT_WDF_WMI_INSTANCE_SET_ITEM EvtWmiInstanceStdDeviceDataSetItem; +EVT_WDF_WMI_INSTANCE_EXECUTE_METHOD EvtWmiInstanceToasterControlExecuteMethod; + +NTSTATUS +ToasterFireArrivalEvent( + _In_ WDFDEVICE Device + ); + +#endif // _TOASTER_H_ + diff --git a/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.inx b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.inx new file mode 100644 index 00000000..2217039d --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.inx @@ -0,0 +1,25 @@ +;Copyright (c) Microsoft Corporation. All rights reserved. + +[Version] +Signature = "$WINDOWS NT$" +Class = System +ClassGuid = {4D36E97D-E325-11CE-BFC1-08002BE10318} +Provider = Contoso +DriverVer = 06/16/1999, 5.00.2064 +CatalogFile = toaster.cat + +[Manufacturer] +Contoso = Contoso, NT$ARCH$ + +[Contoso.NT$ARCH$] +"Basic Toaster" = Toaster_Device, TOASTER\BASIC_TOASTER + +[Toaster_Device.NT] +CopyFiles = Toaster_Device.NT.Copy + +[Toaster_Device.NT.Copy] + +[SourceDisksNames] +1 = "Toaster Device Installation Disk #1",,,"" + +[SourceDisksFiles]
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.vcxproj b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.vcxproj new file mode 100644 index 00000000..cfdfd574 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.vcxproj @@ -0,0 +1,229 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|ARM"> + <Configuration>Debug</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM"> + <Configuration>Release</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|ARM64"> + <Configuration>Debug</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM64"> + <Configuration>Release</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{2D4FC000-01E2-4FDD-B01A-4FD3C59D245D}</ProjectGuid> + <TemplateGuid>{497e31cb-056b-4f31-abb8-447fd55ee5a5}</TemplateGuid> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion> + <Configuration>Debug</Configuration> + <Platform Condition="'$(Platform)' == ''">Win32</Platform> + <RootNamespace>toaster</RootNamespace> + <WindowsTargetPlatformVersion>$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <SupportsPackaging>true</SupportsPackaging> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + <ApiValidator_Enable>true</ApiValidator_Enable> + <OutDir>$(SolutionDir)$(Platform)\$(ConfigurationName)\</OutDir> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <WppEnabled>true</WppEnabled> + <WppRecorderEnabled>true</WppRecorderEnabled> + <WppScanConfigurationData Condition="'%(ClCompile.ScanConfigurationData)' == ''">trace.h</WppScanConfigurationData> + <WppKernelMode>true</WppKernelMode> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <ClCompile> + <WppEnabled>true</WppEnabled> + <WppRecorderEnabled>true</WppRecorderEnabled> + <WppScanConfigurationData Condition="'%(ClCompile.ScanConfigurationData)' == ''">trace.h</WppScanConfigurationData> + <WppKernelMode>true</WppKernelMode> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <WppEnabled>true</WppEnabled> + <WppRecorderEnabled>true</WppRecorderEnabled> + <WppScanConfigurationData Condition="'%(ClCompile.ScanConfigurationData)' == ''">trace.h</WppScanConfigurationData> + <WppKernelMode>true</WppKernelMode> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <WppEnabled>true</WppEnabled> + <WppRecorderEnabled>true</WppRecorderEnabled> + <WppScanConfigurationData Condition="'%(ClCompile.ScanConfigurationData)' == ''">trace.h</WppScanConfigurationData> + <WppKernelMode>true</WppKernelMode> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> + <ClCompile> + <WppEnabled>true</WppEnabled> + <WppRecorderEnabled>true</WppRecorderEnabled> + <WppScanConfigurationData Condition="'%(ClCompile.ScanConfigurationData)' == ''">trace.h</WppScanConfigurationData> + <WppKernelMode>true</WppKernelMode> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> + <ClCompile> + <WppEnabled>true</WppEnabled> + <WppRecorderEnabled>true</WppRecorderEnabled> + <WppScanConfigurationData Condition="'%(ClCompile.ScanConfigurationData)' == ''">trace.h</WppScanConfigurationData> + <WppKernelMode>true</WppKernelMode> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <ClCompile> + <WppEnabled>true</WppEnabled> + <WppRecorderEnabled>true</WppRecorderEnabled> + <WppScanConfigurationData Condition="'%(ClCompile.ScanConfigurationData)' == ''">trace.h</WppScanConfigurationData> + <WppKernelMode>true</WppKernelMode> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <ClCompile> + <WppEnabled>true</WppEnabled> + <WppRecorderEnabled>true</WppRecorderEnabled> + <WppScanConfigurationData Condition="'%(ClCompile.ScanConfigurationData)' == ''">trace.h</WppScanConfigurationData> + <WppKernelMode>true</WppKernelMode> + </ClCompile> + </ItemDefinitionGroup> + <ItemGroup> + <FilesToPackage Include="$(TargetPath)" /> + </ItemGroup> + <ItemGroup> + <Inf Include="toaster.inx" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="driver.h" /> + <ClInclude Include="public.h" /> + <ClInclude Include="toaster.h" /> + <ClInclude Include="trace.h" /> + </ItemGroup> + <ItemGroup> + <ClCompile Include="toaster.c" /> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.vcxproj.filters b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.vcxproj.filters new file mode 100644 index 00000000..2edeb4fc --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/toaster/toaster.vcxproj.filters @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Source Files"> + <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> + <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> + </Filter> + <Filter Include="Header Files"> + <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> + <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> + </Filter> + <Filter Include="Resource Files"> + <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> + <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> + </Filter> + <Filter Include="Driver Files"> + <UniqueIdentifier>{8E41214B-6785-4CFE-B992-037D68949A14}</UniqueIdentifier> + <Extensions>inf;inv;inx;mof;mc;</Extensions> + </Filter> + </ItemGroup> + <ItemGroup> + <Inf Include="toaster.inx"> + <Filter>Driver Files</Filter> + </Inf> + </ItemGroup> + <ItemGroup> + <ClInclude Include="driver.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="public.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="toaster.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="trace.h"> + <Filter>Header Files</Filter> + </ClInclude> + </ItemGroup> + <ItemGroup> + <ClCompile Include="toaster.c"> + <Filter>Source Files</Filter> + </ClCompile> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Driver/toaster/trace.h b/general/WinHEC 2017 Lab/Toaster Driver/toaster/trace.h new file mode 100644 index 00000000..820df2ea --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Driver/toaster/trace.h @@ -0,0 +1,62 @@ +/*++ + +Module Name: + + Trace.h + +Abstract: + + Header file for the debug tracing related function defintions and macros. + +Environment: + + Kernel mode + +--*/ + +// +// Define the tracing flags. +// +// Tracing GUID - f1f5e659-1217-48bd-9c69-6d9cb3a147d5 +// + +#define WPP_CONTROL_GUIDS \ + WPP_DEFINE_CONTROL_GUID( \ + KMDFDriver1TraceGuid, (f1f5e659,1217,48bd,9c69,6d9cb3a147d5), \ + \ + WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ + WPP_DEFINE_BIT(TRACE_DRIVER) \ + WPP_DEFINE_BIT(TRACE_DEVICE) \ + WPP_DEFINE_BIT(TRACE_QUEUE) \ + ) + +#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ + WPP_LEVEL_LOGGER(flag) + +#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ + (WPP_LEVEL_ENABLED(flag) && \ + WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) + +#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ + WPP_LEVEL_LOGGER(flags) + +#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ + (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) + +// +// WPP orders static parameters before dynamic parameters. To support the Trace function +// defined below which sets FLAGS=MYDRIVER_ALL_INFO, a custom macro must be defined to +// reorder the arguments to what the .tpl configuration file expects. +// +#define WPP_RECORDER_FLAGS_LEVEL_ARGS(flags, lvl) WPP_RECORDER_LEVEL_FLAGS_ARGS(lvl, flags) +#define WPP_RECORDER_FLAGS_LEVEL_FILTER(flags, lvl) WPP_RECORDER_LEVEL_FLAGS_FILTER(lvl, flags) + +// +// This comment block is scanned by the trace preprocessor to define our +// Trace function. +// +// begin_wpp config +// FUNC Trace{FLAGS=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); +// FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); +// end_wpp +// diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App.sln b/general/WinHEC 2017 Lab/Toaster Support App/App.sln new file mode 100644 index 00000000..8d28827e --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App.sln @@ -0,0 +1,40 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.12 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CustomCapability", "App\CustomCapability\cpp\CustomCapability.vcxproj", "{0213712B-62E6-5546-8D25-79B90244FFA9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|ARM = Release|ARM + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0213712B-62E6-5546-8D25-79B90244FFA9}.Debug|ARM.ActiveCfg = Debug|ARM + {0213712B-62E6-5546-8D25-79B90244FFA9}.Debug|ARM.Build.0 = Debug|ARM + {0213712B-62E6-5546-8D25-79B90244FFA9}.Debug|ARM.Deploy.0 = Debug|ARM + {0213712B-62E6-5546-8D25-79B90244FFA9}.Debug|x64.ActiveCfg = Debug|x64 + {0213712B-62E6-5546-8D25-79B90244FFA9}.Debug|x64.Build.0 = Debug|x64 + {0213712B-62E6-5546-8D25-79B90244FFA9}.Debug|x64.Deploy.0 = Debug|x64 + {0213712B-62E6-5546-8D25-79B90244FFA9}.Debug|x86.ActiveCfg = Debug|Win32 + {0213712B-62E6-5546-8D25-79B90244FFA9}.Debug|x86.Build.0 = Debug|Win32 + {0213712B-62E6-5546-8D25-79B90244FFA9}.Debug|x86.Deploy.0 = Debug|Win32 + {0213712B-62E6-5546-8D25-79B90244FFA9}.Release|ARM.ActiveCfg = Release|ARM + {0213712B-62E6-5546-8D25-79B90244FFA9}.Release|ARM.Build.0 = Release|ARM + {0213712B-62E6-5546-8D25-79B90244FFA9}.Release|ARM.Deploy.0 = Release|ARM + {0213712B-62E6-5546-8D25-79B90244FFA9}.Release|x64.ActiveCfg = Release|x64 + {0213712B-62E6-5546-8D25-79B90244FFA9}.Release|x64.Build.0 = Release|x64 + {0213712B-62E6-5546-8D25-79B90244FFA9}.Release|x64.Deploy.0 = Release|x64 + {0213712B-62E6-5546-8D25-79B90244FFA9}.Release|x86.ActiveCfg = Release|Win32 + {0213712B-62E6-5546-8D25-79B90244FFA9}.Release|x86.Build.0 = Release|Win32 + {0213712B-62E6-5546-8D25-79B90244FFA9}.Release|x86.Deploy.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/CustomCapability.SCCD b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/CustomCapability.SCCD new file mode 100644 index 00000000..cad58db2 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/CustomCapability.SCCD @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<CustomCapabilityDescriptor xmlns="http://schemas.microsoft.com/appx/2016/sccd" xmlns:s="http://schemas.microsoft.com/appx/2016/sccd"> + <CustomCapabilities> + <CustomCapability Name="microsoft.hsaTestCustomCapability_q536wpkpf5cy2"></CustomCapability> + </CustomCapabilities> + <AuthorizedEntities> + <AuthorizedEntity AppPackageFamilyName="Microsoft.SDKSamples.CustomCapability.CPP_8wekyb3d8bbwe" CertificateSignatureHash="ca9fc964db7e0c2938778f4559946833e7a8cfde0f3eaa07650766d4764e86c4"></AuthorizedEntity> + <AuthorizedEntity AppPackageFamilyName="Microsoft.SDKSamples.CustomCapability.CPP_8wekyb3d8bbwe" CertificateSignatureHash="279cd652c4e252bfbe5217ac722205d7729ba409148cfa9e6d9e5b1cb94eaff1"></AuthorizedEntity> + </AuthorizedEntities> + <Catalog>xxxx</Catalog> +</CustomCapabilityDescriptor> diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/CustomCapability.vcxproj b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/CustomCapability.vcxproj new file mode 100644 index 00000000..8efaa78d --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/CustomCapability.vcxproj @@ -0,0 +1,287 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <ProjectGuid>{0213712b-62e6-5546-8d25-79b90244ffa9}</ProjectGuid> + <RootNamespace>SDKTemplate</RootNamespace> + <DefaultLanguage>en-US</DefaultLanguage> + <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> + <AppContainerApplication>true</AppContainerApplication> + <ApplicationType>Windows Store</ApplicationType> + <WindowsTargetPlatformVersion>10.0.15063.0</WindowsTargetPlatformVersion> + <WindowsTargetPlatformMinVersion>10.0.15063.0</WindowsTargetPlatformMinVersion> + <ApplicationTypeRevision>10.0</ApplicationTypeRevision> + <ProjectName>CustomCapability</ProjectName> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|ARM"> + <Configuration>Debug</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM"> + <Configuration>Release</Configuration> + <Platform>ARM</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>v141</PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>v141</PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>v141</PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <WholeProgramOptimization>true</WholeProgramOptimization> + <PlatformToolset>v141</PlatformToolset> + <UseDotNetNativeToolchain>true</UseDotNetNativeToolchain> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <WholeProgramOptimization>true</WholeProgramOptimization> + <PlatformToolset>v141</PlatformToolset> + <UseDotNetNativeToolchain>true</UseDotNetNativeToolchain> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <WholeProgramOptimization>true</WholeProgramOptimization> + <PlatformToolset>v141</PlatformToolset> + <UseDotNetNativeToolchain>true</UseDotNetNativeToolchain> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props" Condition="exists('$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props')" /> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props" Condition="exists('$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props" Condition="exists('$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props')" /> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props" Condition="exists('$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props" Condition="exists('$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props')" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props" Condition="exists('$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPlatformExtensionSDKLocation(`WindowsDesktop, Version=10.0.15063.0`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), $(SDKReferenceDirectoryRoot), $(SDKExtensionDirectoryRoot), $(SDKReferenceRegistryRoot)))\DesignTime\CommonConfiguration\Neutral\WindowsDesktop.props')" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup> + <IncludePath>$(IncludePath);..\..\..\SharedContent\cpp</IncludePath> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)\</OutDir> + <IntDir>$(Platform)\$(Configuration)\</IntDir> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions> + <DisableSpecificWarnings>4453;28204</DisableSpecificWarnings> + <AdditionalIncludeDirectories>$(ProjectDir);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories);$(OutDir)..</AdditionalIncludeDirectories> + <ShowIncludes>false</ShowIncludes> + </ClCompile> + <Link> + <AdditionalDependencies>vccorlib.lib;WindowsApp.lib;%(AdditionalDependencies);rpcrt4.lib</AdditionalDependencies> + <OptimizeReferences>false</OptimizeReferences> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> + <ClCompile> + <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions> + <DisableSpecificWarnings>4453;28204</DisableSpecificWarnings> + <AdditionalIncludeDirectories>$(ProjectDir);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories);$(OutDir)..</AdditionalIncludeDirectories> + <ShowIncludes>false</ShowIncludes> + </ClCompile> + <Link> + <AdditionalDependencies>vccorlib.lib;WindowsApp.lib;%(AdditionalDependencies);rpcrt4.lib</AdditionalDependencies> + <OptimizeReferences>false</OptimizeReferences> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <ClCompile> + <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions> + <DisableSpecificWarnings>4453;28204</DisableSpecificWarnings> + <AdditionalIncludeDirectories>$(ProjectDir);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories);$(OutDir)..</AdditionalIncludeDirectories> + <ShowIncludes>false</ShowIncludes> + </ClCompile> + <Link> + <AdditionalDependencies>vccorlib.lib;WindowsApp.lib;%(AdditionalDependencies);rpcrt4.lib</AdditionalDependencies> + <OptimizeReferences>true</OptimizeReferences> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> + <ClCompile> + <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions> + <DisableSpecificWarnings>4453;28204</DisableSpecificWarnings> + <AdditionalIncludeDirectories>$(ProjectDir);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories);$(OutDir)..</AdditionalIncludeDirectories> + <ShowIncludes>false</ShowIncludes> + </ClCompile> + <Link> + <AdditionalDependencies>vccorlib.lib;WindowsApp.lib;%(AdditionalDependencies);rpcrt4.lib</AdditionalDependencies> + <OptimizeReferences>true</OptimizeReferences> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions> + <DisableSpecificWarnings>4453;28204</DisableSpecificWarnings> + <AdditionalIncludeDirectories>$(ProjectDir);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories);$(OutDir)..</AdditionalIncludeDirectories> + <ShowIncludes>false</ShowIncludes> + </ClCompile> + <Link> + <AdditionalDependencies>vccorlib.lib;WindowsApp.lib;%(AdditionalDependencies);rpcrt4.lib</AdditionalDependencies> + <OptimizeReferences>false</OptimizeReferences> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions> + <DisableSpecificWarnings>4453;28204</DisableSpecificWarnings> + <AdditionalIncludeDirectories>$(ProjectDir);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories);$(OutDir)..</AdditionalIncludeDirectories> + <ShowIncludes>false</ShowIncludes> + </ClCompile> + <Link> + <AdditionalDependencies>vccorlib.lib;WindowsApp.lib;%(AdditionalDependencies);rpcrt4.lib</AdditionalDependencies> + <OptimizeReferences>true</OptimizeReferences> + </Link> + </ItemDefinitionGroup> + <ItemGroup> + <ClInclude Include="ServiceViewModel.h" /> + <ClInclude Include="pch.h" /> + <ClInclude Include="..\..\..\SharedContent\cpp\App.xaml.h"> + <DependentUpon>..\..\..\SharedContent\xaml\App.xaml</DependentUpon> + </ClInclude> + <ClInclude Include="..\..\..\SharedContent\cpp\MainPage.xaml.h"> + <DependentUpon>..\..\..\SharedContent\cpp\MainPage.xaml</DependentUpon> + </ClInclude> + <ClInclude Include="Scenario1_MeteringData.xaml.h"> + <DependentUpon>Scenario1_MeteringData.xaml</DependentUpon> + </ClInclude> + <ClInclude Include="RpcClient.h" /> + <ClInclude Include="SampleConfiguration.h" /> + </ItemGroup> + <ItemGroup> + <ApplicationDefinition Include="..\..\..\SharedContent\xaml\App.xaml"> + <SubType>Designer</SubType> + </ApplicationDefinition> + <Page Include="..\..\..\SharedContent\xaml\Styles.xaml"> + <Link>Styles\Styles.xaml</Link> + </Page> + <Page Include="..\..\..\SharedContent\cpp\MainPage.xaml"> + <SubType>Designer</SubType> + </Page> + <Page Include="Scenario1_MeteringData.xaml"> + <SubType>Designer</SubType> + </Page> + </ItemGroup> + <ItemGroup> + <AppxManifest Include="Package.appxmanifest"> + <SubType>Designer</SubType> + </AppxManifest> + </ItemGroup> + <ItemGroup> + <Image Include="..\..\..\SharedContent\media\microsoft-sdk.png"> + <Link>Assets\microsoft-sdk.png</Link> + </Image> + <Image Include="..\..\..\SharedContent\media\smalltile-sdk.png"> + <Link>Assets\smalltile-sdk.png</Link> + </Image> + <Image Include="..\..\..\SharedContent\media\splash-sdk.png"> + <Link>Assets\splash-sdk.png</Link> + </Image> + <Image Include="..\..\..\SharedContent\media\squaretile-sdk.png"> + <Link>Assets\squaretile-sdk.png</Link> + </Image> + <Image Include="..\..\..\SharedContent\media\storelogo-sdk.png"> + <Link>Assets\storelogo-sdk.png</Link> + </Image> + <Image Include="..\..\..\SharedContent\media\tile-sdk.png"> + <Link>Assets\tile-sdk.png</Link> + </Image> + <Image Include="..\..\..\SharedContent\media\windows-sdk.png"> + <Link>Assets\windows-sdk.png</Link> + </Image> + </ItemGroup> + <ItemGroup> + <ClCompile Include="RpcInterface.c"> + <CompileAsWinRT>false</CompileAsWinRT> + <PrecompiledHeader>NotUsing</PrecompiledHeader> + </ClCompile> + <ClCompile Include="..\..\..\SharedContent\cpp\App.xaml.cpp"> + <DependentUpon>..\..\..\SharedContent\xaml\App.xaml</DependentUpon> + </ClCompile> + <ClCompile Include="..\..\..\SharedContent\cpp\MainPage.xaml.cpp"> + <DependentUpon>..\..\..\SharedContent\cpp\MainPage.xaml</DependentUpon> + </ClCompile> + <ClCompile Include="ServiceViewModel.cpp" /> + <ClCompile Include="Scenario1_MeteringData.xaml.cpp"> + <DependentUpon>Scenario1_MeteringData.xaml</DependentUpon> + </ClCompile> + <ClCompile Include="SampleConfiguration.cpp" /> + <ClCompile Include="pch.cpp"> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader> + </ClCompile> + <ClCompile Include="RpcClient.cpp"> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader> + </ClCompile> + </ItemGroup> + <ItemGroup> + <SDKReference Include="WindowsDesktop, Version=10.0.15063.0" /> + </ItemGroup> + <ItemGroup> + <None Include="..\..\..\..\Toaster Driver\Service\RpcInterface.acf" /> + </ItemGroup> + <ItemGroup> + <Midl Include="..\..\..\..\Toaster Driver\Service\RpcInterface.Idl" /> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/CustomCapability.vcxproj.filters b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/CustomCapability.vcxproj.filters new file mode 100644 index 00000000..af84bc38 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/CustomCapability.vcxproj.filters @@ -0,0 +1,89 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Common"> + <UniqueIdentifier>81d95eea-286c-4a5e-98f1-eef612020bf0</UniqueIdentifier> + </Filter> + <Filter Include="Assets"> + <UniqueIdentifier>85b464d3-9e56-4242-b58b-1f226dd034b4</UniqueIdentifier> + <Extensions>bmp;fbx;gif;jpg;jpeg;tga;tiff;tif;png</Extensions> + </Filter> + <Filter Include="ViewModel"> + <UniqueIdentifier>{1c0f2943-52c2-4a54-93a2-971c14e7c8ec}</UniqueIdentifier> + </Filter> + <Filter Include="Model"> + <UniqueIdentifier>{33085be2-4c37-4eab-8f6e-6add0cffe2d4}</UniqueIdentifier> + </Filter> + </ItemGroup> + <ItemGroup> + <ApplicationDefinition Include="..\..\..\SharedContent\xaml\App.xaml" /> + </ItemGroup> + <ItemGroup> + <ClCompile Include="pch.cpp" /> + <ClCompile Include="RpcClient.cpp"> + <Filter>Model</Filter> + </ClCompile> + <ClCompile Include="SampleConfiguration.cpp"> + <Filter>Common</Filter> + </ClCompile> + <ClCompile Include="Scenario1_MeteringData.xaml.cpp" /> + <ClCompile Include="..\..\..\SharedContent\cpp\App.xaml.cpp" /> + <ClCompile Include="..\..\..\SharedContent\cpp\MainPage.xaml.cpp" /> + <ClCompile Include="ServiceViewModel.cpp"> + <Filter>ViewModel</Filter> + </ClCompile> + <ClCompile Include="RpcInterface.c" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="pch.h" /> + <ClInclude Include="RpcClient.h"> + <Filter>Model</Filter> + </ClInclude> + <ClInclude Include="SampleConfiguration.h"> + <Filter>Common</Filter> + </ClInclude> + <ClInclude Include="Scenario1_MeteringData.xaml.h" /> + <ClInclude Include="..\..\..\SharedContent\cpp\App.xaml.h" /> + <ClInclude Include="..\..\..\SharedContent\cpp\MainPage.xaml.h" /> + <ClInclude Include="ServiceViewModel.h"> + <Filter>ViewModel</Filter> + </ClInclude> + </ItemGroup> + <ItemGroup> + <Image Include="..\..\..\SharedContent\media\microsoft-sdk.png"> + <Filter>Assets</Filter> + </Image> + <Image Include="..\..\..\SharedContent\media\smalltile-sdk.png"> + <Filter>Assets</Filter> + </Image> + <Image Include="..\..\..\SharedContent\media\splash-sdk.png"> + <Filter>Assets</Filter> + </Image> + <Image Include="..\..\..\SharedContent\media\squaretile-sdk.png"> + <Filter>Assets</Filter> + </Image> + <Image Include="..\..\..\SharedContent\media\storelogo-sdk.png"> + <Filter>Assets</Filter> + </Image> + <Image Include="..\..\..\SharedContent\media\tile-sdk.png"> + <Filter>Assets</Filter> + </Image> + <Image Include="..\..\..\SharedContent\media\windows-sdk.png"> + <Filter>Assets</Filter> + </Image> + </ItemGroup> + <ItemGroup> + <AppxManifest Include="Package.appxmanifest" /> + </ItemGroup> + <ItemGroup> + <Page Include="Scenario1_MeteringData.xaml" /> + <Page Include="..\..\..\SharedContent\xaml\Styles.xaml" /> + <Page Include="..\..\..\SharedContent\cpp\MainPage.xaml" /> + </ItemGroup> + <ItemGroup> + <None Include="..\..\..\..\Toaster Driver\Service\RpcInterface.acf" /> + </ItemGroup> + <ItemGroup> + <Midl Include="..\..\..\..\Toaster Driver\Service\RpcInterface.Idl" /> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/DeviceList.cpp b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/DeviceList.cpp new file mode 100644 index 00000000..cb3a7a8e --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/DeviceList.cpp @@ -0,0 +1,244 @@ +#include "pch.h" +#include "DeviceList.h" +#include "MainPage.xaml.h" +#include "App.xaml.h" + +using namespace SDKTemplate; + +using namespace Platform; +using namespace Platform::Collections; +using namespace Windows::ApplicationModel; +using namespace Windows::Devices::Enumeration; +using namespace Windows::Devices::Custom; +using namespace Windows::Foundation; +using namespace Windows::UI::Core; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Documents; + +DeviceList^ DeviceList::_Current = nullptr; + +DeviceList^ DeviceList::Current::get() +{ + if (DeviceList::_Current == nullptr) + { + DeviceList::_Current = ref new DeviceList(); + } + return DeviceList::_Current; +} + +DeviceList::DeviceList() : m_WatcherStarted(false), m_WatcherSuspended(false) +{ + m_Fx2Watcher = nullptr; + m_List = ref new Vector<DeviceListEntry^>(); + InitDeviceWatcher(); + + // Register for app suspend/resume handlers + App::Current->Suspending += ref new SuspendingEventHandler(this, &DeviceList::SuspendDeviceWatcher); + App::Current->Resuming += ref new EventHandler<Object^>(this, &DeviceList::ResumeDeviceWatcher); +} + +void DeviceList::InitDeviceWatcher() +{ + // Define the selector to enumerate all of the fx2 device interface class instances. + // Use the DeviceInterfaceGuid provided by the driver (Fx2Driver, in this case). + auto selector = CustomDevice::GetDeviceSelector(Fx2Driver::DeviceInterfaceGuid); + + // Set of properties to retrieve + auto properties = ref new Vector<String^>({ "System.Devices.DeviceInstanceId" }); + + // Create a device watcher to look for instances of the fx2 device interface. + m_Fx2Watcher = DeviceInformation::CreateWatcher(selector, properties); + + m_Fx2Watcher->Added += ref new TypedEventHandler<DeviceWatcher^, DeviceInformation^>(this, &DeviceList::OnFx2Added); + m_Fx2Watcher->Removed += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>(this, &DeviceList::OnFx2Removed); + m_Fx2Watcher->EnumerationCompleted += ref new TypedEventHandler<DeviceWatcher^, Object^>(this, &DeviceList::OnFx2EnumerationComplete); +} + +void DeviceList::StartFx2Watcher() +{ + MainPage::Current->NotifyUser("starting device watcher", NotifyType::StatusMessage); + + std::for_each( + begin(m_List), + end(m_List), + [](DeviceListEntry^ Entry) { + Entry->Matched = false; + }); + + WatcherStarted = true; + m_Fx2Watcher->Start(); +} + +void DeviceList::StopFx2Watcher() +{ + MainPage::Current->NotifyUser("stopping fx2 watcher", NotifyType::StatusMessage); + m_Fx2Watcher->Stop(); + WatcherStarted = false; +} + +void DeviceList::CreateBooleanTable( + InlineCollection^ Table, + const Platform::Array<bool>^ NewValues, + const Platform::Array<bool>^ OldValues, + String^ /* IndexTitle */, + String^ /* ValueTitle */, + String^ TrueValue, + String^ FalseValue) +{ + Table->Clear(); + + for (int i = 0; i < (int)NewValues->Length; i += 1) + { + auto line = ref new Span(); + auto block = ref new Run(); + block->Text = (i + 1).ToString(); + line->Inlines->Append(block); + + block = ref new Run(); + block->Text = " "; + line->Inlines->Append(block); + + block = ref new Run(); + block->Text = NewValues[i] ? TrueValue : FalseValue; + + if ((OldValues != nullptr) && (OldValues[i] != NewValues[i])) + { + auto bold = ref new Bold(); + bold->Inlines->Append(block); + line->Inlines->Append(bold); + } + else + { + line->Inlines->Append(block); + } + + line->Inlines->Append(ref new LineBreak()); + + Table->Append(line); + } +} + +DeviceListEntry^ DeviceList::FindDevice(String^ Id) +{ + auto i = std::find_if( + begin(m_List), + end(m_List), + [Id](DeviceListEntry^ e) {return e->Id == Id; }); + + if (i == end(m_List)) + { + return nullptr; + } + else + { + return *i; + } +} + +void DeviceList::OnFx2Added(DeviceWatcher ^ /* Sender */, DeviceInformation^ DevInterface) +{ + MainPage::Current->Dispatcher->RunAsync( + CoreDispatcherPriority::Normal, + ref new DispatchedHandler( + [this, DevInterface]()->void + { + MainPage::Current->NotifyUser("OnFx2Added: " + DevInterface->Id, NotifyType::StatusMessage); + + // search the device list for a device with a matching interface ID + auto match = FindDevice(DevInterface->Id); + + // If we found a match then mark it as verified and return + if (match != nullptr) + { + match->Matched = true; + return; + } + + // Create a new elemetn for this device interface, and queue up the query of its + // device information + match = ref new DeviceListEntry(DevInterface); + + // Add the new element to the end of the list of devices + m_List->Append(match); + })); +} + +void DeviceList::OnFx2Removed(DeviceWatcher ^ /* Sender */, DeviceInformationUpdate^ DevInterface) +{ + auto deviceId = DevInterface->Id; + + MainPage::Current->Dispatcher->RunAsync( + CoreDispatcherPriority::Normal, + ref new DispatchedHandler( + [this, deviceId]() + { + MainPage::Current->NotifyUser("OnFx2Removed: " + deviceId, NotifyType::StatusMessage); + + // Search the list of devices for one with a matching ID. Move the matched + // item to the end of the list. + auto i = std::remove_if( + begin(m_List), + end(m_List), + [deviceId](DeviceListEntry^ e) {return e->Id == deviceId; }); + + // if there's no match return. + if (i == end(m_List)) + { + return; + } + + // Remove the last item from the list. + MainPage::Current->NotifyUser("OnFx2Removed: " + deviceId + " removed", NotifyType::StatusMessage); + m_List->RemoveAtEnd(); + })); +} + +void DeviceList::OnFx2EnumerationComplete(DeviceWatcher ^ /* Sender */, Object ^ /* o */) +{ + MainPage::Current->Dispatcher->RunAsync( + CoreDispatcherPriority::Normal, + ref new DispatchedHandler( + [this]() + { + MainPage::Current->NotifyUser("OnFx2EnumerationComplete", NotifyType::StatusMessage); + + DeviceList^ me = this; + + // Move all the unmatched elements to the end of the list + auto i = std::remove_if( + begin(m_List), + end(m_List), + [](DeviceListEntry^ e) { return e->Matched == false; }); + + // Determine the number of unmatched entries + auto unmatchedCount = end(m_List) - i; + + while (unmatchedCount > 0) + { + m_List->RemoveAtEnd(); + unmatchedCount -= 1; + } + })); +} + +void DeviceList::SuspendDeviceWatcher(Object^, SuspendingEventArgs^) +{ + if (WatcherStarted) + { + m_WatcherSuspended = true; + StopFx2Watcher(); + } + else + { + m_WatcherSuspended = false; + } +} + +void DeviceList::ResumeDeviceWatcher(Object^, Object^) +{ + if (m_WatcherSuspended) + { + m_WatcherSuspended = false; + StartFx2Watcher(); + } +} diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Package.appxmanifest b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Package.appxmanifest new file mode 100644 index 00000000..0ec45a07 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Package.appxmanifest @@ -0,0 +1,41 @@ +<?xml version='1.0' encoding='utf-8'?> +<Package + xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" + xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" + xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" + xmlns:uap4="http://schemas.microsoft.com/appx/manifest/uap/windows10/4" + IgnorableNamespaces="uap mp uap4" + > + <Identity Name="Microsoft.SDKSamples.CustomCapability.CPP" Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" Version="1.0.0.0" /> + <mp:PhoneIdentity PhoneProductId="26388851-6c33-4124-b1e5-96e859da28bf" PhonePublisherId="00000000-0000-0000-0000-000000000000"/> + <Properties> + <DisplayName>Custom Capability C++ Sample</DisplayName> + <PublisherDisplayName>Microsoft Corporation</PublisherDisplayName> + <Logo>Assets\StoreLogo-sdk.png</Logo> + </Properties> + <Dependencies> + <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.15063.0" MaxVersionTested="10.0.15063.0"/> + </Dependencies> + <Resources> + <Resource Language="x-generate"/> + </Resources> + <Applications> + <Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="CustomCapability.App"> + <uap:VisualElements + DisplayName="Custom Capability C++ sample" + Square150x150Logo="Assets\squareTile-sdk.png" + Square44x44Logo="Assets\smallTile-sdk.png" + Description="Hsa C++ sample" + BackgroundColor="#00B2F0" + > + <uap:SplashScreen Image="Assets\splash-sdk.png"/> + <uap:DefaultTile> + <uap:ShowNameOnTiles> + <uap:ShowOn Tile="square150x150Logo"/> + </uap:ShowNameOnTiles> + </uap:DefaultTile> + </uap:VisualElements> + </Application> + </Applications> + +</Package> diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcClient.cpp b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcClient.cpp new file mode 100644 index 00000000..870d6306 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcClient.cpp @@ -0,0 +1,177 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +// There is an error in the system header files that incorrectly +// places RpcStringBindingCompose in the app partition. +// Work around it by changing the WINAPI_FAMILY to desktop temporarily. +#pragma push_macro("WINAPI_FAMILY") +#undef WINAPI_FAMILY +#define WINAPI_FAMILY WINAPI_FAMILY_DESKTOP_APP +#include "RpcClient.h" +#pragma pop_macro("WINAPI_FAMILY") + +using namespace SDKTemplate; + +__int64 RpcClient::Initialize() +{ + RPC_STATUS status; + RPC_WSTR pszStringBinding = nullptr; + + status = RpcStringBindingCompose( + NULL, + reinterpret_cast<RPC_WSTR>(L"ncalrpc"), + NULL, + reinterpret_cast<RPC_WSTR>(RPC_STATIC_ENDPOINT), + NULL, + &pszStringBinding); + + if (status) + { + goto error_status; + } + + status = RpcBindingFromStringBinding( + pszStringBinding, + &hRpcBinding); + + if (status) + { + goto error_status; + } + + status = RpcStringFree(&pszStringBinding); + + if (status) + { + goto error_status; + } + + RpcTryExcept + { + ::RemoteOpen(hRpcBinding, &phContext); + } + RpcExcept(1) + { + status = RpcExceptionCode(); + } + RpcEndExcept + +error_status: + + return status; +} + +// +// Make RPC call to start metering. This is a blocking call and +// will return only after StopMetering is called. +// +__int64 RpcClient::StartMeteringAndWaitForStop(__int64 samplePeriod) +{ + __int64 ulCode = 0; + CallbackCount = 0; + MeteringData = 0; + + RpcTryExcept + { + ::StartMetering(phContext, samplePeriod, (__int64)this); + } + RpcExcept(1) + { + ulCode = RpcExceptionCode(); + } + RpcEndExcept + + return ulCode; +} + + +// +// Make rpc call SetSampleRate +// +__int64 RpcClient::SetSampleRate(int rate) +{ + __int64 ulCode = 0; + RpcTryExcept + { + ::SetSamplePeriod(phContext, rate); + } + RpcExcept(1) + { + ulCode = RpcExceptionCode(); + } + RpcEndExcept + return ulCode; +} + +// +// Make rpc call StopMetering +// +__int64 RpcClient::StopMetering() +{ + __int64 ulCode = 0; + RpcTryExcept + { + ::StopMetering(phContext); + } + RpcExcept(1) + { + ulCode = RpcExceptionCode(); + } + RpcEndExcept + return ulCode; +} + +RpcClient::~RpcClient() +{ + RPC_STATUS status; + + if (hRpcBinding != NULL) + { + RpcTryExcept + { + ::RemoteClose(&phContext); + } + RpcExcept(1) + { + // Ignoring the result of RemoteClose as nothing can be + // done on the client side with this return code + status = RpcExceptionCode(); + } + RpcEndExcept + + status = RpcBindingFree(&hRpcBinding); + hRpcBinding = NULL; + } +} + +// +// Metering rpc callback +// +void MeteringDataEvent(__int64 data, __int64 context) +{ + RpcClient* client = static_cast<RpcClient*>((PVOID)context); + client->MeteringData = data; + ++client->CallbackCount; +} + +///******************************************************/ +///* MIDL allocate and free */ +///******************************************************/ + +void __RPC_FAR * __RPC_USER midl_user_allocate(size_t len) +{ + return(malloc(len)); +} + +void __RPC_USER midl_user_free(void __RPC_FAR * ptr) +{ + free(ptr); +}
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcClient.h b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcClient.h new file mode 100644 index 00000000..0ee5ff78 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcClient.h @@ -0,0 +1,30 @@ +// +// RpcClient.h +// + +#pragma once + +#define RPC_STATIC_ENDPOINT L"HsaSampleRpcEndpoint" + +#include "RpcInterface_h.h" + +namespace SDKTemplate +{ + /// <summary> + /// Client side RPC implementation + /// </summary> + private class RpcClient sealed + { + public: + ~RpcClient(); + __int64 Initialize(); + __int64 StartMeteringAndWaitForStop(__int64 samplePeriod); + __int64 StopMetering(); + __int64 SetSampleRate(int rate); + int CallbackCount; + __int64 MeteringData; + private: + handle_t hRpcBinding; + PCONTEXT_HANDLE_TYPE phContext; + }; +} diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface.c b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface.c new file mode 100644 index 00000000..0f988533 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface.c @@ -0,0 +1,6 @@ +// RpcInterface_c.c expects _ARM_ to be set when building for ARM. +#ifdef _M_ARM +#define _ARM_ 1 +#endif + +#include "RpcInterface_c.c" diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface_c.c b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface_c.c new file mode 100644 index 00000000..8b05c1ea --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface_c.c @@ -0,0 +1,476 @@ + + +/* this ALWAYS GENERATED file contains the RPC client stubs */ + + + /* File created by MIDL compiler version 8.01.0622 */ +/* at Mon Jan 18 19:14:07 2038 + */ +/* Compiler settings for C:\WinHEC 2017 Lab\Toaster Driver\Service\RpcInterface.Idl: + Oicf, W1, Zp8, env=Win64 (32b run), target_arch=AMD64 8.01.0622 + protocol : dce , ms_ext, c_ext, robust + error checks: allocation ref bounds_check enum stub_data + VC __declspec() decoration level: + __declspec(uuid()), __declspec(selectany), __declspec(novtable) + DECLSPEC_UUID(), MIDL_INTERFACE() +*/ +/* @@MIDL_FILE_HEADING( ) */ + +#if defined(_M_AMD64) + + +#pragma warning( disable: 4049 ) /* more than 64k source lines */ +#if _MSC_VER >= 1200 +#pragma warning(push) +#endif + +#pragma warning( disable: 4211 ) /* redefine extern to static */ +#pragma warning( disable: 4232 ) /* dllimport identity*/ +#pragma warning( disable: 4024 ) /* array to pointer mapping*/ + +#include <string.h> + +#include "RpcInterface_h.h" + +#define TYPE_FORMAT_STRING_SIZE 23 +#define PROC_FORMAT_STRING_SIZE 245 +#define EXPR_FORMAT_STRING_SIZE 1 +#define TRANSMIT_AS_TABLE_SIZE 0 +#define WIRE_MARSHAL_TABLE_SIZE 0 + +typedef struct _RpcInterface_MIDL_TYPE_FORMAT_STRING + { + short Pad; + unsigned char Format[ TYPE_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_TYPE_FORMAT_STRING; + +typedef struct _RpcInterface_MIDL_PROC_FORMAT_STRING + { + short Pad; + unsigned char Format[ PROC_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_PROC_FORMAT_STRING; + +typedef struct _RpcInterface_MIDL_EXPR_FORMAT_STRING + { + long Pad; + unsigned char Format[ EXPR_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_EXPR_FORMAT_STRING; + + +static const RPC_SYNTAX_IDENTIFIER _RpcTransferSyntax = +{{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}}; + + +extern const RpcInterface_MIDL_TYPE_FORMAT_STRING RpcInterface__MIDL_TypeFormatString; +extern const RpcInterface_MIDL_PROC_FORMAT_STRING RpcInterface__MIDL_ProcFormatString; +extern const RpcInterface_MIDL_EXPR_FORMAT_STRING RpcInterface__MIDL_ExprFormatString; + +#define GENERIC_BINDING_TABLE_SIZE 0 + + +/* Standard interface: RpcInterface, ver. 1.0, + GUID={0x906B0CE0,0xC70B,0x1067,{0xB3,0x17,0x00,0xDD,0x01,0x06,0x62,0xDA}} */ + + +extern const MIDL_SERVER_INFO RpcInterface_ServerInfo; + + +extern const RPC_DISPATCH_TABLE RpcInterface_v1_0_DispatchTable; + +static const RPC_CLIENT_INTERFACE RpcInterface___RpcClientInterface = + { + sizeof(RPC_CLIENT_INTERFACE), + {{0x906B0CE0,0xC70B,0x1067,{0xB3,0x17,0x00,0xDD,0x01,0x06,0x62,0xDA}},{1,0}}, + {{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}}, + (RPC_DISPATCH_TABLE*)&RpcInterface_v1_0_DispatchTable, + 0, + 0, + 0, + &RpcInterface_ServerInfo, + 0x04000000 + }; +RPC_IF_HANDLE RpcInterface_v1_0_c_ifspec = (RPC_IF_HANDLE)& RpcInterface___RpcClientInterface; + +extern const MIDL_STUB_DESC RpcInterface_StubDesc; + +static RPC_BINDING_HANDLE RpcInterface__MIDL_AutoBindHandle; + + +void RemoteOpen( + /* [in] */ handle_t hBinding, + /* [out] */ PPCONTEXT_HANDLE_TYPE pphContext) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[0], + hBinding, + pphContext); + +} + + +void RemoteClose( + /* [out][in] */ PPCONTEXT_HANDLE_TYPE pphContext) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[36], + pphContext); + +} + + +void StartMetering( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext, + /* [in] */ __int64 samplePeriod, + /* [optional][in] */ __int64 context) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[74], + phContext, + samplePeriod, + context); + +} + + +void SetSamplePeriod( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext, + /* [in] */ __int64 samplePeriod) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[124], + phContext, + samplePeriod); + +} + + +void StopMetering( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[168], + phContext); + +} + + +#if !defined(__RPC_WIN64__) +#error Invalid build platform for this stub. +#endif + +static const RpcInterface_MIDL_PROC_FORMAT_STRING RpcInterface__MIDL_ProcFormatString = + { + 0, + { + + /* Procedure RemoteOpen */ + + 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 2 */ NdrFcLong( 0x0 ), /* 0 */ +/* 6 */ NdrFcShort( 0x0 ), /* 0 */ +/* 8 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 10 */ 0x32, /* FC_BIND_PRIMITIVE */ + 0x0, /* 0 */ +/* 12 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 14 */ NdrFcShort( 0x0 ), /* 0 */ +/* 16 */ NdrFcShort( 0x38 ), /* 56 */ +/* 18 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 20 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 22 */ NdrFcShort( 0x0 ), /* 0 */ +/* 24 */ NdrFcShort( 0x0 ), /* 0 */ +/* 26 */ NdrFcShort( 0x0 ), /* 0 */ +/* 28 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter pphContext */ + +/* 30 */ NdrFcShort( 0x110 ), /* Flags: out, simple ref, */ +/* 32 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 34 */ NdrFcShort( 0x6 ), /* Type Offset=6 */ + + /* Procedure RemoteClose */ + +/* 36 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 38 */ NdrFcLong( 0x0 ), /* 0 */ +/* 42 */ NdrFcShort( 0x1 ), /* 1 */ +/* 44 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 46 */ 0x30, /* FC_BIND_CONTEXT */ + 0xe0, /* Ctxt flags: via ptr, in, out, */ +/* 48 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 50 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 52 */ NdrFcShort( 0x38 ), /* 56 */ +/* 54 */ NdrFcShort( 0x38 ), /* 56 */ +/* 56 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 58 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 60 */ NdrFcShort( 0x0 ), /* 0 */ +/* 62 */ NdrFcShort( 0x0 ), /* 0 */ +/* 64 */ NdrFcShort( 0x0 ), /* 0 */ +/* 66 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter pphContext */ + +/* 68 */ NdrFcShort( 0x118 ), /* Flags: in, out, simple ref, */ +/* 70 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 72 */ NdrFcShort( 0xe ), /* Type Offset=14 */ + + /* Procedure StartMetering */ + +/* 74 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 76 */ NdrFcLong( 0x0 ), /* 0 */ +/* 80 */ NdrFcShort( 0x2 ), /* 2 */ +/* 82 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ +/* 84 */ 0x30, /* FC_BIND_CONTEXT */ + 0x40, /* Ctxt flags: in, */ +/* 86 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 88 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 90 */ NdrFcShort( 0x44 ), /* 68 */ +/* 92 */ NdrFcShort( 0x0 ), /* 0 */ +/* 94 */ 0x40, /* Oi2 Flags: has ext, */ + 0x3, /* 3 */ +/* 96 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 98 */ NdrFcShort( 0x0 ), /* 0 */ +/* 100 */ NdrFcShort( 0x0 ), /* 0 */ +/* 102 */ NdrFcShort( 0x0 ), /* 0 */ +/* 104 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 106 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 108 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 110 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Parameter samplePeriod */ + +/* 112 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 114 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 116 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Parameter context */ + +/* 118 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 120 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 122 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Procedure SetSamplePeriod */ + +/* 124 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 126 */ NdrFcLong( 0x0 ), /* 0 */ +/* 130 */ NdrFcShort( 0x3 ), /* 3 */ +/* 132 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 134 */ 0x30, /* FC_BIND_CONTEXT */ + 0x40, /* Ctxt flags: in, */ +/* 136 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 138 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 140 */ NdrFcShort( 0x34 ), /* 52 */ +/* 142 */ NdrFcShort( 0x0 ), /* 0 */ +/* 144 */ 0x40, /* Oi2 Flags: has ext, */ + 0x2, /* 2 */ +/* 146 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 148 */ NdrFcShort( 0x0 ), /* 0 */ +/* 150 */ NdrFcShort( 0x0 ), /* 0 */ +/* 152 */ NdrFcShort( 0x0 ), /* 0 */ +/* 154 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 156 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 158 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 160 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Parameter samplePeriod */ + +/* 162 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 164 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 166 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Procedure StopMetering */ + +/* 168 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 170 */ NdrFcLong( 0x0 ), /* 0 */ +/* 174 */ NdrFcShort( 0x4 ), /* 4 */ +/* 176 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 178 */ 0x30, /* FC_BIND_CONTEXT */ + 0x40, /* Ctxt flags: in, */ +/* 180 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 182 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 184 */ NdrFcShort( 0x24 ), /* 36 */ +/* 186 */ NdrFcShort( 0x0 ), /* 0 */ +/* 188 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 190 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 192 */ NdrFcShort( 0x0 ), /* 0 */ +/* 194 */ NdrFcShort( 0x0 ), /* 0 */ +/* 196 */ NdrFcShort( 0x0 ), /* 0 */ +/* 198 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 200 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 202 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 204 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Procedure MeteringDataEvent */ + +/* 206 */ 0x34, /* FC_CALLBACK_HANDLE */ + 0x48, /* Old Flags: */ +/* 208 */ NdrFcLong( 0x0 ), /* 0 */ +/* 212 */ NdrFcShort( 0x0 ), /* 0 */ +/* 214 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 216 */ NdrFcShort( 0x20 ), /* 32 */ +/* 218 */ NdrFcShort( 0x0 ), /* 0 */ +/* 220 */ 0x40, /* Oi2 Flags: has ext, */ + 0x2, /* 2 */ +/* 222 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 224 */ NdrFcShort( 0x0 ), /* 0 */ +/* 226 */ NdrFcShort( 0x0 ), /* 0 */ +/* 228 */ NdrFcShort( 0x0 ), /* 0 */ +/* 230 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter data */ + +/* 232 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 234 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 236 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Parameter context */ + +/* 238 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 240 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 242 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + 0x0 + } + }; + +static const RpcInterface_MIDL_TYPE_FORMAT_STRING RpcInterface__MIDL_TypeFormatString = + { + 0, + { + NdrFcShort( 0x0 ), /* 0 */ +/* 2 */ + 0x11, 0x4, /* FC_RP [alloced_on_stack] */ +/* 4 */ NdrFcShort( 0x2 ), /* Offset= 2 (6) */ +/* 6 */ 0x30, /* FC_BIND_CONTEXT */ + 0xa0, /* Ctxt flags: via ptr, out, */ +/* 8 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 10 */ + 0x11, 0x4, /* FC_RP [alloced_on_stack] */ +/* 12 */ NdrFcShort( 0x2 ), /* Offset= 2 (14) */ +/* 14 */ 0x30, /* FC_BIND_CONTEXT */ + 0xe1, /* Ctxt flags: via ptr, in, out, can't be null */ +/* 16 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 18 */ 0x30, /* FC_BIND_CONTEXT */ + 0x41, /* Ctxt flags: in, can't be null */ +/* 20 */ 0x0, /* 0 */ + 0x0, /* 0 */ + + 0x0 + } + }; + +static const unsigned short RpcInterface_FormatStringOffsetTable[] = + { + 0, + 36, + 74, + 124, + 168, + }; + + +static const unsigned short _callbackRpcInterface_FormatStringOffsetTable[] = + { + 206 + }; + + +static const MIDL_STUB_DESC RpcInterface_StubDesc = + { + (void *)& RpcInterface___RpcClientInterface, + MIDL_user_allocate, + MIDL_user_free, + &RpcInterface__MIDL_AutoBindHandle, + 0, + 0, + 0, + 0, + RpcInterface__MIDL_TypeFormatString.Format, + 1, /* -error bounds_check flag */ + 0x50002, /* Ndr library version */ + 0, + 0x801026e, /* MIDL Version 8.1.622 */ + 0, + 0, + 0, /* notify & notify_flag routine table */ + 0x1, /* MIDL flag */ + 0, /* cs routines */ + 0, /* proxy/server info */ + 0 + }; + +static const RPC_DISPATCH_FUNCTION RpcInterface_table[] = + { + NdrServerCall2, + 0 + }; +static const RPC_DISPATCH_TABLE RpcInterface_v1_0_DispatchTable = + { + 1, + (RPC_DISPATCH_FUNCTION*)RpcInterface_table + }; + +static const SERVER_ROUTINE RpcInterface_ServerRoutineTable[] = + { + (SERVER_ROUTINE)MeteringDataEvent + }; + +static const MIDL_SERVER_INFO RpcInterface_ServerInfo = + { + &RpcInterface_StubDesc, + RpcInterface_ServerRoutineTable, + RpcInterface__MIDL_ProcFormatString.Format, + _callbackRpcInterface_FormatStringOffsetTable, + 0, + 0, + 0, + 0}; +#if _MSC_VER >= 1200 +#pragma warning(pop) +#endif + + +#endif /* defined(_M_AMD64)*/ + diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface_h.h b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface_h.h new file mode 100644 index 00000000..a0e2dcac --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface_h.h @@ -0,0 +1,112 @@ + + +/* this ALWAYS GENERATED file contains the definitions for the interfaces */ + + + /* File created by MIDL compiler version 8.01.0622 */ +/* at Mon Jan 18 19:14:07 2038 + */ +/* Compiler settings for C:\WinHEC 2017 Lab\Toaster Driver\Service\RpcInterface.Idl: + Oicf, W1, Zp8, env=Win64 (32b run), target_arch=AMD64 8.01.0622 + protocol : dce , ms_ext, c_ext, robust + error checks: allocation ref bounds_check enum stub_data + VC __declspec() decoration level: + __declspec(uuid()), __declspec(selectany), __declspec(novtable) + DECLSPEC_UUID(), MIDL_INTERFACE() +*/ +/* @@MIDL_FILE_HEADING( ) */ + +#pragma warning( disable: 4049 ) /* more than 64k source lines */ + + +/* verify that the <rpcndr.h> version is high enough to compile this file*/ +#ifndef __REQUIRED_RPCNDR_H_VERSION__ +#define __REQUIRED_RPCNDR_H_VERSION__ 475 +#endif + +#include "rpc.h" +#include "rpcndr.h" + +#ifndef __RPCNDR_H_VERSION__ +#error this stub requires an updated version of <rpcndr.h> +#endif /* __RPCNDR_H_VERSION__ */ + + +#ifndef __RpcInterface_h_h__ +#define __RpcInterface_h_h__ + +#if defined(_MSC_VER) && (_MSC_VER >= 1020) +#pragma once +#endif + +#if defined(__cplusplus) +#if defined(__MIDL_USE_C_ENUM) +#define MIDL_ENUM enum +#else +#define MIDL_ENUM enum class +#endif +#endif + + +/* Forward Declarations */ + +/* header files for imported files */ +#include "oaidl.h" + +#ifdef __cplusplus +extern "C"{ +#endif + + +#ifndef __RpcInterface_INTERFACE_DEFINED__ +#define __RpcInterface_INTERFACE_DEFINED__ + +/* interface RpcInterface */ +/* [unique][version][uuid] */ + +typedef /* [context_handle] */ void *PCONTEXT_HANDLE_TYPE; + +typedef /* [ref] */ PCONTEXT_HANDLE_TYPE *PPCONTEXT_HANDLE_TYPE; + +void RemoteOpen( + /* [in] */ handle_t hBinding, + /* [out] */ PPCONTEXT_HANDLE_TYPE pphContext); + +void RemoteClose( + /* [out][in] */ PPCONTEXT_HANDLE_TYPE pphContext); + +void StartMetering( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext, + /* [in] */ __int64 samplePeriod, + /* [optional][in] */ __int64 context); + +void SetSamplePeriod( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext, + /* [in] */ __int64 samplePeriod); + +void StopMetering( + /* [in] */ PCONTEXT_HANDLE_TYPE phContext); + +/* [callback] */ void MeteringDataEvent( + /* [in] */ __int64 data, + /* [optional][in] */ __int64 context); + + + +extern RPC_IF_HANDLE RpcInterface_v1_0_c_ifspec; +extern RPC_IF_HANDLE RpcInterface_v1_0_s_ifspec; +#endif /* __RpcInterface_INTERFACE_DEFINED__ */ + +/* Additional Prototypes for ALL interfaces */ + +void __RPC_USER PCONTEXT_HANDLE_TYPE_rundown( PCONTEXT_HANDLE_TYPE ); + +/* end of Additional Prototypes */ + +#ifdef __cplusplus +} +#endif + +#endif + + diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface_s.c b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface_s.c new file mode 100644 index 00000000..ec58170d --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/RpcInterface_s.c @@ -0,0 +1,430 @@ + + +/* this ALWAYS GENERATED file contains the RPC server stubs */ + + + /* File created by MIDL compiler version 8.01.0622 */ +/* at Mon Jan 18 19:14:07 2038 + */ +/* Compiler settings for C:\WinHEC 2017 Lab\Toaster Driver\Service\RpcInterface.Idl: + Oicf, W1, Zp8, env=Win64 (32b run), target_arch=AMD64 8.01.0622 + protocol : dce , ms_ext, c_ext, robust + error checks: allocation ref bounds_check enum stub_data + VC __declspec() decoration level: + __declspec(uuid()), __declspec(selectany), __declspec(novtable) + DECLSPEC_UUID(), MIDL_INTERFACE() +*/ +/* @@MIDL_FILE_HEADING( ) */ + +#if defined(_M_AMD64) + + +#pragma warning( disable: 4049 ) /* more than 64k source lines */ +#if _MSC_VER >= 1200 +#pragma warning(push) +#endif + +#pragma warning( disable: 4211 ) /* redefine extern to static */ +#pragma warning( disable: 4232 ) /* dllimport identity*/ +#pragma warning( disable: 4024 ) /* array to pointer mapping*/ + +#include <string.h> +#include "RpcInterface_h.h" + +#define TYPE_FORMAT_STRING_SIZE 23 +#define PROC_FORMAT_STRING_SIZE 245 +#define EXPR_FORMAT_STRING_SIZE 1 +#define TRANSMIT_AS_TABLE_SIZE 0 +#define WIRE_MARSHAL_TABLE_SIZE 0 + +typedef struct _RpcInterface_MIDL_TYPE_FORMAT_STRING + { + short Pad; + unsigned char Format[ TYPE_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_TYPE_FORMAT_STRING; + +typedef struct _RpcInterface_MIDL_PROC_FORMAT_STRING + { + short Pad; + unsigned char Format[ PROC_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_PROC_FORMAT_STRING; + +typedef struct _RpcInterface_MIDL_EXPR_FORMAT_STRING + { + long Pad; + unsigned char Format[ EXPR_FORMAT_STRING_SIZE ]; + } RpcInterface_MIDL_EXPR_FORMAT_STRING; + + +static const RPC_SYNTAX_IDENTIFIER _RpcTransferSyntax = +{{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}}; + +extern const RpcInterface_MIDL_TYPE_FORMAT_STRING RpcInterface__MIDL_TypeFormatString; +extern const RpcInterface_MIDL_PROC_FORMAT_STRING RpcInterface__MIDL_ProcFormatString; +extern const RpcInterface_MIDL_EXPR_FORMAT_STRING RpcInterface__MIDL_ExprFormatString; + +/* Standard interface: RpcInterface, ver. 1.0, + GUID={0x906B0CE0,0xC70B,0x1067,{0xB3,0x17,0x00,0xDD,0x01,0x06,0x62,0xDA}} */ + + +extern const MIDL_SERVER_INFO RpcInterface_ServerInfo; + +extern const RPC_DISPATCH_TABLE RpcInterface_v1_0_DispatchTable; + +static const RPC_SERVER_INTERFACE RpcInterface___RpcServerInterface = + { + sizeof(RPC_SERVER_INTERFACE), + {{0x906B0CE0,0xC70B,0x1067,{0xB3,0x17,0x00,0xDD,0x01,0x06,0x62,0xDA}},{1,0}}, + {{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}}, + (RPC_DISPATCH_TABLE*)&RpcInterface_v1_0_DispatchTable, + 0, + 0, + 0, + &RpcInterface_ServerInfo, + 0x04000000 + }; +RPC_IF_HANDLE RpcInterface_v1_0_s_ifspec = (RPC_IF_HANDLE)& RpcInterface___RpcServerInterface; + +extern const MIDL_STUB_DESC RpcInterface_StubDesc; + + extern const MIDL_STUBLESS_PROXY_INFO RpcInterface_ProxyInfo; + +/* [callback] */ void MeteringDataEvent( + /* [in] */ __int64 data, + /* [optional][in] */ __int64 context) +{ + + NdrClientCall2( + ( PMIDL_STUB_DESC )&RpcInterface_StubDesc, + (PFORMAT_STRING) &RpcInterface__MIDL_ProcFormatString.Format[206], + data, + context); + +} + +extern const NDR_RUNDOWN RundownRoutines[]; + +#if !defined(__RPC_WIN64__) +#error Invalid build platform for this stub. +#endif + +static const RpcInterface_MIDL_PROC_FORMAT_STRING RpcInterface__MIDL_ProcFormatString = + { + 0, + { + + /* Procedure RemoteOpen */ + + 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 2 */ NdrFcLong( 0x0 ), /* 0 */ +/* 6 */ NdrFcShort( 0x0 ), /* 0 */ +/* 8 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 10 */ 0x32, /* FC_BIND_PRIMITIVE */ + 0x0, /* 0 */ +/* 12 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 14 */ NdrFcShort( 0x0 ), /* 0 */ +/* 16 */ NdrFcShort( 0x38 ), /* 56 */ +/* 18 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 20 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 22 */ NdrFcShort( 0x0 ), /* 0 */ +/* 24 */ NdrFcShort( 0x0 ), /* 0 */ +/* 26 */ NdrFcShort( 0x0 ), /* 0 */ +/* 28 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter pphContext */ + +/* 30 */ NdrFcShort( 0x110 ), /* Flags: out, simple ref, */ +/* 32 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 34 */ NdrFcShort( 0x6 ), /* Type Offset=6 */ + + /* Procedure RemoteClose */ + +/* 36 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 38 */ NdrFcLong( 0x0 ), /* 0 */ +/* 42 */ NdrFcShort( 0x1 ), /* 1 */ +/* 44 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 46 */ 0x30, /* FC_BIND_CONTEXT */ + 0xe0, /* Ctxt flags: via ptr, in, out, */ +/* 48 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 50 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 52 */ NdrFcShort( 0x38 ), /* 56 */ +/* 54 */ NdrFcShort( 0x38 ), /* 56 */ +/* 56 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 58 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 60 */ NdrFcShort( 0x0 ), /* 0 */ +/* 62 */ NdrFcShort( 0x0 ), /* 0 */ +/* 64 */ NdrFcShort( 0x0 ), /* 0 */ +/* 66 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter pphContext */ + +/* 68 */ NdrFcShort( 0x118 ), /* Flags: in, out, simple ref, */ +/* 70 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 72 */ NdrFcShort( 0xe ), /* Type Offset=14 */ + + /* Procedure StartMetering */ + +/* 74 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 76 */ NdrFcLong( 0x0 ), /* 0 */ +/* 80 */ NdrFcShort( 0x2 ), /* 2 */ +/* 82 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ +/* 84 */ 0x30, /* FC_BIND_CONTEXT */ + 0x40, /* Ctxt flags: in, */ +/* 86 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 88 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 90 */ NdrFcShort( 0x44 ), /* 68 */ +/* 92 */ NdrFcShort( 0x0 ), /* 0 */ +/* 94 */ 0x40, /* Oi2 Flags: has ext, */ + 0x3, /* 3 */ +/* 96 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 98 */ NdrFcShort( 0x0 ), /* 0 */ +/* 100 */ NdrFcShort( 0x0 ), /* 0 */ +/* 102 */ NdrFcShort( 0x0 ), /* 0 */ +/* 104 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 106 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 108 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 110 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Parameter samplePeriod */ + +/* 112 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 114 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 116 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Parameter context */ + +/* 118 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 120 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 122 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Procedure SetSamplePeriod */ + +/* 124 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 126 */ NdrFcLong( 0x0 ), /* 0 */ +/* 130 */ NdrFcShort( 0x3 ), /* 3 */ +/* 132 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 134 */ 0x30, /* FC_BIND_CONTEXT */ + 0x40, /* Ctxt flags: in, */ +/* 136 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 138 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 140 */ NdrFcShort( 0x34 ), /* 52 */ +/* 142 */ NdrFcShort( 0x0 ), /* 0 */ +/* 144 */ 0x40, /* Oi2 Flags: has ext, */ + 0x2, /* 2 */ +/* 146 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 148 */ NdrFcShort( 0x0 ), /* 0 */ +/* 150 */ NdrFcShort( 0x0 ), /* 0 */ +/* 152 */ NdrFcShort( 0x0 ), /* 0 */ +/* 154 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 156 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 158 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 160 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Parameter samplePeriod */ + +/* 162 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 164 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 166 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Procedure StopMetering */ + +/* 168 */ 0x0, /* 0 */ + 0x48, /* Old Flags: */ +/* 170 */ NdrFcLong( 0x0 ), /* 0 */ +/* 174 */ NdrFcShort( 0x4 ), /* 4 */ +/* 176 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 178 */ 0x30, /* FC_BIND_CONTEXT */ + 0x40, /* Ctxt flags: in, */ +/* 180 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 182 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 184 */ NdrFcShort( 0x24 ), /* 36 */ +/* 186 */ NdrFcShort( 0x0 ), /* 0 */ +/* 188 */ 0x40, /* Oi2 Flags: has ext, */ + 0x1, /* 1 */ +/* 190 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 192 */ NdrFcShort( 0x0 ), /* 0 */ +/* 194 */ NdrFcShort( 0x0 ), /* 0 */ +/* 196 */ NdrFcShort( 0x0 ), /* 0 */ +/* 198 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter phContext */ + +/* 200 */ NdrFcShort( 0x8 ), /* Flags: in, */ +/* 202 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 204 */ NdrFcShort( 0x12 ), /* Type Offset=18 */ + + /* Procedure MeteringDataEvent */ + +/* 206 */ 0x34, /* FC_CALLBACK_HANDLE */ + 0x48, /* Old Flags: */ +/* 208 */ NdrFcLong( 0x0 ), /* 0 */ +/* 212 */ NdrFcShort( 0x0 ), /* 0 */ +/* 214 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 216 */ NdrFcShort( 0x20 ), /* 32 */ +/* 218 */ NdrFcShort( 0x0 ), /* 0 */ +/* 220 */ 0x40, /* Oi2 Flags: has ext, */ + 0x2, /* 2 */ +/* 222 */ 0xa, /* 10 */ + 0x1, /* Ext Flags: new corr desc, */ +/* 224 */ NdrFcShort( 0x0 ), /* 0 */ +/* 226 */ NdrFcShort( 0x0 ), /* 0 */ +/* 228 */ NdrFcShort( 0x0 ), /* 0 */ +/* 230 */ NdrFcShort( 0x0 ), /* 0 */ + + /* Parameter data */ + +/* 232 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 234 */ NdrFcShort( 0x0 ), /* X64 Stack size/offset = 0 */ +/* 236 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + /* Parameter context */ + +/* 238 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 240 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 242 */ 0xb, /* FC_HYPER */ + 0x0, /* 0 */ + + 0x0 + } + }; + +static const RpcInterface_MIDL_TYPE_FORMAT_STRING RpcInterface__MIDL_TypeFormatString = + { + 0, + { + NdrFcShort( 0x0 ), /* 0 */ +/* 2 */ + 0x11, 0x4, /* FC_RP [alloced_on_stack] */ +/* 4 */ NdrFcShort( 0x2 ), /* Offset= 2 (6) */ +/* 6 */ 0x30, /* FC_BIND_CONTEXT */ + 0xa0, /* Ctxt flags: via ptr, out, */ +/* 8 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 10 */ + 0x11, 0x4, /* FC_RP [alloced_on_stack] */ +/* 12 */ NdrFcShort( 0x2 ), /* Offset= 2 (14) */ +/* 14 */ 0x30, /* FC_BIND_CONTEXT */ + 0xe1, /* Ctxt flags: via ptr, in, out, can't be null */ +/* 16 */ 0x0, /* 0 */ + 0x0, /* 0 */ +/* 18 */ 0x30, /* FC_BIND_CONTEXT */ + 0x41, /* Ctxt flags: in, can't be null */ +/* 20 */ 0x0, /* 0 */ + 0x0, /* 0 */ + + 0x0 + } + }; + +static const NDR_RUNDOWN RundownRoutines[] = + { + PCONTEXT_HANDLE_TYPE_rundown + }; + + +static const unsigned short RpcInterface_FormatStringOffsetTable[] = + { + 0, + 36, + 74, + 124, + 168, + }; + + +static const unsigned short _callbackRpcInterface_FormatStringOffsetTable[] = + { + 206 + }; + + +static const MIDL_STUB_DESC RpcInterface_StubDesc = + { + (void *)& RpcInterface___RpcServerInterface, + MIDL_user_allocate, + MIDL_user_free, + 0, + RundownRoutines, + 0, + 0, + 0, + RpcInterface__MIDL_TypeFormatString.Format, + 1, /* -error bounds_check flag */ + 0x50002, /* Ndr library version */ + 0, + 0x801026e, /* MIDL Version 8.1.622 */ + 0, + 0, + 0, /* notify & notify_flag routine table */ + 0x1, /* MIDL flag */ + 0, /* cs routines */ + 0, /* proxy/server info */ + 0 + }; + +static const RPC_DISPATCH_FUNCTION RpcInterface_table[] = + { + NdrServerCall2, + NdrServerCall2, + NdrServerCall2, + NdrServerCall2, + NdrServerCall2, + 0 + }; +static const RPC_DISPATCH_TABLE RpcInterface_v1_0_DispatchTable = + { + 5, + (RPC_DISPATCH_FUNCTION*)RpcInterface_table + }; + +static const SERVER_ROUTINE RpcInterface_ServerRoutineTable[] = + { + (SERVER_ROUTINE)RemoteOpen, + (SERVER_ROUTINE)RemoteClose, + (SERVER_ROUTINE)StartMetering, + (SERVER_ROUTINE)SetSamplePeriod, + (SERVER_ROUTINE)StopMetering, + }; + +static const MIDL_SERVER_INFO RpcInterface_ServerInfo = + { + &RpcInterface_StubDesc, + RpcInterface_ServerRoutineTable, + RpcInterface__MIDL_ProcFormatString.Format, + RpcInterface_FormatStringOffsetTable, + 0, + 0, + 0, + 0}; +#if _MSC_VER >= 1200 +#pragma warning(pop) +#endif + + +#endif /* defined(_M_AMD64)*/ + diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/SampleConfiguration.cpp b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/SampleConfiguration.cpp new file mode 100644 index 00000000..a808cf83 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/SampleConfiguration.cpp @@ -0,0 +1,21 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include "MainPage.xaml.h" +#include "SampleConfiguration.h" + +using namespace SDKTemplate; + +Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario> +{ + { "Connect to an NT Service", "SDKTemplate.MeteringData" }, +}; diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/SampleConfiguration.h b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/SampleConfiguration.h new file mode 100644 index 00000000..22581275 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/SampleConfiguration.h @@ -0,0 +1,47 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once +#include "pch.h" + +namespace SDKTemplate +{ + value struct Scenario; + + partial ref class MainPage + { + internal: + static property Platform::String^ FEATURE_NAME + { + Platform::String^ get() + { + return "Custom Capability C++ sample"; + } + } + + static property Platform::Array<Scenario>^ scenarios + { + Platform::Array<Scenario>^ get() + { + return scenariosInner; + } + } + + private: + static Platform::Array<Scenario>^ scenariosInner; + }; + + public value struct Scenario + { + Platform::String^ Title; + Platform::String^ ClassName; + }; +} diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Scenario1_MeteringData.xaml b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Scenario1_MeteringData.xaml new file mode 100644 index 00000000..0636f74d --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Scenario1_MeteringData.xaml @@ -0,0 +1,68 @@ +<!-- +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* +--> +<Page + x:Class="SDKTemplate.MeteringData" + xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + xmlns:d="http://schemas.microsoft.com/expression/blend/2008" + xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" + mc:Ignorable="d"> + + <ScrollViewer Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Padding="12,10,12,12"> + <Grid> + <Grid.RowDefinitions> + <RowDefinition Height="Auto"/> + <RowDefinition Height="*"/> + </Grid.RowDefinitions> + <StackPanel Margin="0,0,0,10"> + <TextBlock Text="Description:" Style="{StaticResource SampleHeaderTextStyle}"/> + <TextBlock Style="{StaticResource ScenarioDescriptionTextStyle}" TextWrapping="Wrap"> + This scenario demonstrates RPC communication between an app and an NT service. For demonstration purposes, the service reads data from an imaginary device. + </TextBlock> + <StackPanel BorderThickness="2" BorderBrush="{ThemeResource ButtonBorderThemeBrush}" Margin="0,10,0,0" Padding="5"> + <TextBlock TextWrapping="Wrap"> + <Run FontWeight="Bold" Text="Step 1: Choose a period at which the samples will be pushed from the NT service"/> + </TextBlock> + <TextBlock TextWrapping="Wrap" Margin="0,10,5,0"> + Sample Period (ms): <Run Text="{x:Bind SamplePeriodSlider.Value, Mode=OneWay}"/> + </TextBlock> + <Slider x:Name="SamplePeriodSlider" HorizontalAlignment="Left" Width="300" IsEnabled="{x:Bind ViewModel.SliderEnabled, Mode=OneWay}" VerticalAlignment="Top" Minimum="1" Maximum="1000" ValueChanged="slider_ValueChanged" FontSize="20" Value="{x:Bind ViewModel.SliderValue, Mode=OneWay}"/> + </StackPanel> + <StackPanel BorderThickness="2" BorderBrush="{ThemeResource ButtonBorderThemeBrush}" Margin="0,10,0,0" Padding="5"> + <TextBlock TextWrapping="Wrap"> + <Run FontWeight="Bold" Text="Step 2: Click start to receive samples from the NT service"/> + </TextBlock> + <StackPanel Orientation="Horizontal" Margin="0,10,0,0"> + <Button IsEnabled="{x:Bind ViewModel.StartButtonEnabled, Mode=OneWay}" Content="Start" Click="button_Click_StartMetering"/> + <Button IsEnabled="{x:Bind ViewModel.StopButtonEnabled, Mode=OneWay}" Content="Stop" Click="button_Click_StopMetering" Margin="10,0,0,0"/> + </StackPanel> + </StackPanel> + <StackPanel BorderThickness="2" BorderBrush="{ThemeResource ButtonBorderThemeBrush}" Margin="0,10,0,0" Padding="5"> + <TextBlock TextWrapping="Wrap"> + <Run FontWeight="Bold" Text="Step 3: Observe the expected and actual incoming sample rate"/> + </TextBlock> + <TextBlock Margin="0,10,0,0"> + Expected Sample Rate: <Run Text="{x:Bind ViewModel.ExpectedRpcCallbackRate, Mode=OneWay}"/> + </TextBlock> + <TextBlock Margin="0,10,0,0"> + Actual Sample Rate: <Run Text="{x:Bind ViewModel.ActualRpcCallbackRate, Mode=OneWay}"/> + </TextBlock> + </StackPanel> + <TextBlock FontWeight="Bold" Margin="0,10,0,0" Text="Samples:"/> + </StackPanel> + <ScrollViewer Grid.Row="2" HorizontalAlignment="Stretch" Margin="0,10,0,0" VerticalAlignment="Stretch"> + <TextBox Height="400" IsReadOnly="true" HorizontalAlignment="Stretch" Text="{x:Bind ViewModel.SampleMessage, Mode=OneWay}" BorderThickness="0"/> + </ScrollViewer> + </Grid> + </ScrollViewer> +</Page> diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Scenario1_MeteringData.xaml.cpp b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Scenario1_MeteringData.xaml.cpp new file mode 100644 index 00000000..3a9e1f48 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Scenario1_MeteringData.xaml.cpp @@ -0,0 +1,47 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include "Scenario1_MeteringData.xaml.h" + +using namespace SDKTemplate; + +using namespace Platform; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Controls::Primitives; + +MeteringData::MeteringData() +{ + InitializeComponent(); + ViewModel = ref new ServiceViewModel(); +} + +void SDKTemplate::MeteringData::button_Click_StartMetering(Object^ sender, RoutedEventArgs^ e) +{ + ViewModel->StartMetering((int)SamplePeriodSlider->Value); +} + +void SDKTemplate::MeteringData::button_Click_StopMetering(Object^ sender, RoutedEventArgs^ e) +{ + ViewModel->StopMetering(); +} + +void SDKTemplate::MeteringData::slider_ValueChanged(Object^ sender, RangeBaseValueChangedEventArgs^ e) +{ + // Ignore slider value changes prior to ViewModel initialization. + if (ViewModel != nullptr) + { + // Update the sample period in response to slider change. + ViewModel->SetSamplePeriod((int)SamplePeriodSlider->Value); + } +} diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Scenario1_MeteringData.xaml.h b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Scenario1_MeteringData.xaml.h new file mode 100644 index 00000000..79faa4f3 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/Scenario1_MeteringData.xaml.h @@ -0,0 +1,31 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once + +#include "Scenario1_MeteringData.g.h" +#include "ServiceViewModel.h" + +namespace SDKTemplate +{ + [Windows::Foundation::Metadata::WebHostHidden] + public ref class MeteringData sealed + { + public: + MeteringData(); + property ServiceViewModel^ ViewModel; + + private: + void button_Click_StartMetering(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); + void button_Click_StopMetering(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); + void slider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e); + }; +} diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/ServiceViewModel.cpp b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/ServiceViewModel.cpp new file mode 100644 index 00000000..9f9674c4 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/ServiceViewModel.cpp @@ -0,0 +1,282 @@ +#include "pch.h" +#include "ServiceViewModel.h" +#include "MainPage.xaml.h" + +using namespace Concurrency; +using namespace Platform; +using namespace SDKTemplate; +using namespace Windows::System::Threading; +using namespace Windows::UI::Xaml::Data; + +ServiceViewModel::ServiceViewModel() +{ + // Set default rate + samplePeriod = 100; + + // Initialize UI state + startButtonEnabled = true; + stopButtonEnabled = false; + sliderEnabled = true; + sliderValue = samplePeriod; + actualRpcCallbackRate = "0"; + expectedRpcCallbackRate = "0"; + + meteringOn = false; + + // Get the dispatcher for notifying property change + dispatcher = Windows::UI::Core::CoreWindow::GetForCurrentThread()->Dispatcher; + + sampleArray = ref new Platform::Array<__int64>(1000); +} + +// +// if errCode represents an error, then display a message and return true. +// +inline bool ServiceViewModel::NotifyIfAnyError(__int64 errCode) +{ + if (errCode != 0) + { + meteringOn = false; + NotifyStatusMessage("Error occured while communicating with RPC server: " + errCode.ToString(), NotifyType::ErrorMessage); + + // Reset button state + StartButtonEnabled = true; + StopButtonEnabled = false; + return true; + } + return false; +} + +// Bindable properties +#pragma region BindableProperties + +String^ ServiceViewModel::ExpectedRpcCallbackRate::get() { return expectedRpcCallbackRate; } +void ServiceViewModel::ExpectedRpcCallbackRate::set(String^ value) +{ + if (expectedRpcCallbackRate != value) + { + expectedRpcCallbackRate = value; + NotifyPropertyChanged("ExpectedRpcCallbackRate"); + } +} + +String^ ServiceViewModel::ActualRpcCallbackRate::get() { return actualRpcCallbackRate; } +void ServiceViewModel::ActualRpcCallbackRate::set(String^ value) +{ + if (actualRpcCallbackRate != value) + { + actualRpcCallbackRate = value; + NotifyPropertyChanged("ActualRpcCallbackRate"); + } +} + +String^ ServiceViewModel::SampleMessage::get() { return sampleMessage; } +void ServiceViewModel::SampleMessage::set(String^ value) +{ + if (sampleMessage != value) + { + sampleMessage = value; + NotifyPropertyChanged("SampleMessage"); + } +} + +bool ServiceViewModel::StartButtonEnabled::get() { return startButtonEnabled; } +void ServiceViewModel::StartButtonEnabled::set(bool value) +{ + if (startButtonEnabled != value) + { + startButtonEnabled = value; + NotifyPropertyChanged("StartButtonEnabled"); + } +} + +bool ServiceViewModel::StopButtonEnabled::get() { return stopButtonEnabled; } +void ServiceViewModel::StopButtonEnabled::set(bool value) +{ + if (stopButtonEnabled != value) + { + stopButtonEnabled = value; + NotifyPropertyChanged("StopButtonEnabled"); + } +} + +bool ServiceViewModel::SliderEnabled::get() { return sliderEnabled; } +void ServiceViewModel::SliderEnabled::set(bool value) +{ + if (sliderEnabled != value) + { + sliderEnabled = value; + NotifyPropertyChanged("SliderEnabled"); + } +} + +double ServiceViewModel::SliderValue::get() { return sliderValue; } +void ServiceViewModel::SliderValue::set(double value) +{ + if (sliderValue != value) + { + sliderValue = value; + NotifyPropertyChanged("SliderValue"); + } +} +#pragma endregion BindableProperties + +void SDKTemplate::ServiceViewModel::NotifyPropertyChanged(Platform::String^ prop) +{ + if (dispatcher != nullptr) + { + dispatcher->RunAsync( + Windows::UI::Core::CoreDispatcherPriority::Normal, + ref new Windows::UI::Core::DispatchedHandler([this, prop]() + { + PropertyChangedEventArgs^ args = + ref new PropertyChangedEventArgs(prop); + PropertyChanged(this, args); + })); + } + // else log error +} + +// +// Initializes rpcclient and metering +// +void ServiceViewModel::StartMetering(int sampleRate) +{ + create_task([this, sampleRate] + { + SampleMessage = ""; + StartButtonEnabled = false; + StopButtonEnabled = true; + stopMeteringRequested = false; + + rpcclient = std::make_unique<RpcClient>(); + if (NotifyIfAnyError(rpcclient->Initialize())) return; + + meteringOn = true; + sampleRefreshCount = 0; + sampleArray[0] = 0; + + // Set the sample rate on server + this->samplePeriod = sampleRate; + __int64 retCode = rpcclient->SetSampleRate(sampleRate); + + FILETIME initialSystemTime; + GetSystemTimeAsFileTime(&initialSystemTime); + lastUpdateTime.LowPart = initialSystemTime.dwLowDateTime; + lastUpdateTime.HighPart = initialSystemTime.dwHighDateTime; + + if (!NotifyIfAnyError(retCode)) + { + // Set up worker for UI update. + Windows::Foundation::TimeSpan span{ 100 * 10000 }; // 100ms refresh rate + + auto timerHandler = ref new TimerElapsedHandler([this](ThreadPoolTimer^) + { + __int64 meteringData = rpcclient->MeteringData; + + // If there is no new data, return + if (sampleArray[0] == meteringData) + { + return; + } + + // Arithmetic subtraction of time + // https://msdn.microsoft.com/en-us/library/ms724950%28VS.85%29.aspx?f=255&MSPPError=-2147217396 + FILETIME currentSystemTime; + ULARGE_INTEGER currentTimeUi; + GetSystemTimeAsFileTime(¤tSystemTime); + currentTimeUi.LowPart = currentSystemTime.dwLowDateTime; + currentTimeUi.HighPart = currentSystemTime.dwHighDateTime; + + // Calculate number of samples received since last callback + __int64 now = rpcclient->CallbackCount; + __int64 diff = now - rpcDataCountOld; + rpcDataCountOld = now; + + // Calculate incoming sample rate + double rate = (double)diff*1E7 / (currentTimeUi.QuadPart - lastUpdateTime.QuadPart); + ExpectedRpcCallbackRate = (1E3 / this->samplePeriod).ToString() + " /sec"; + lastUpdateTime = currentTimeUi; + + ActualRpcCallbackRate = rate.ToString() + " /sec"; + + // Construct the sample data string + String^ sampleMessage = meteringData + "\n"; + unsigned int length = sampleArray->Length; + if (sampleRefreshCount < length) + { + ++sampleRefreshCount; + length = sampleRefreshCount; + } + + // Insert the new data point at the top of the array. + // Old data falls off the end of the array. + for (unsigned int i = 1; i < length; ++i) + { + sampleArray[i] = sampleArray[i - 1]; + sampleMessage += sampleArray[i] + "\n"; + } + sampleArray[0] = meteringData; + + SampleMessage = sampleMessage; + }); + + ThreadPoolTimer^ periodicTimer = ThreadPoolTimer::CreatePeriodicTimer(timerHandler, span); + NotifyStatusMessage("Metering start command sent successfully", NotifyType::StatusMessage); + retCode = this->rpcclient->StartMeteringAndWaitForStop(sampleRate); + meteringOn = false; + periodicTimer->Cancel(); + if (!NotifyIfAnyError(retCode) && !stopMeteringRequested) + { + NotifyStatusMessage("Rpc server connection closed without stop metering being requested", + NotifyType::ErrorMessage); + StartButtonEnabled = true; + StopButtonEnabled = false; + } + } + }); +} + +// +// Stop metering +// +void ServiceViewModel::StopMetering() +{ + create_task([this] + { + StopButtonEnabled = false; + SliderEnabled = false; + stopMeteringRequested = true; + + __int64 retCode = this->rpcclient->StopMetering(); + if (!NotifyIfAnyError(retCode)) + { + NotifyStatusMessage("Metering stop command sent successfully", + NotifyType::StatusMessage); + } + + SliderEnabled = true; + StartButtonEnabled = true; + }); +} + +// +// Set sample period +// +void ServiceViewModel::SetSamplePeriod(int samplePeriod) +{ + create_task([this, samplePeriod] + { + this->samplePeriod = samplePeriod; + if (meteringOn) + { + _int64 retCode = rpcclient->SetSampleRate(samplePeriod); + if (!NotifyIfAnyError(retCode)) + { + NotifyStatusMessage( + "Sample period set to: " + samplePeriod, + NotifyType::StatusMessage); + } + } + }); +}
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/ServiceViewModel.h b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/ServiceViewModel.h new file mode 100644 index 00000000..c2fcad0c --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/ServiceViewModel.h @@ -0,0 +1,77 @@ +#pragma once + +#include "RpcClient.h" +#include <memory> + +namespace SDKTemplate +{ + [Windows::UI::Xaml::Data::Bindable] + public ref class ServiceViewModel sealed : Windows::UI::Xaml::Data::INotifyPropertyChanged + { + public: + ServiceViewModel(); + void StartMetering(int sampleRate); + void SetSamplePeriod(int rate); + void StopMetering(); + property Platform::String^ ExpectedRpcCallbackRate + { + Platform::String^ get(); + void set(Platform::String^ value); + } + property Platform::String^ ActualRpcCallbackRate + { + Platform::String^ get(); + void set(Platform::String^ value); + } + property Platform::String^ SampleMessage + { + Platform::String^ get(); + void set(Platform::String^ value); + } + property bool StartButtonEnabled + { + bool get(); + void set(bool value); + } + property bool StopButtonEnabled + { + bool get(); + void set(bool value); + } + property bool SliderEnabled + { + bool get(); + void set(bool value); + } + property double SliderValue + { + double get(); + void set(double value); + } + virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged; + + private: + volatile bool meteringOn; + Windows::UI::Core::ICoreDispatcher^ dispatcher; + int samplePeriod; + ULARGE_INTEGER lastUpdateTime; + __int64 rpcDataCountOld = 0; + unsigned int sampleRefreshCount = 0; + std::unique_ptr<RpcClient> rpcclient; + bool stopMeteringRequested; + bool NotifyIfAnyError(__int64 errCode); + + // Variables backing UI bindings + Platform::String^ sampleMessage; + Platform::String^ expectedRpcCallbackRate; + Platform::String^ actualRpcCallbackRate; + bool startButtonEnabled; + bool stopButtonEnabled; + bool sliderEnabled; + double sliderValue; + + void NotifyPropertyChanged(Platform::String^ prop); + + Platform::Array<__int64>^ sampleArray; + }; +} diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/pch.cpp b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/pch.cpp new file mode 100644 index 00000000..b300c4c0 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/pch.cpp @@ -0,0 +1,60 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +// +// pch.cpp +// Include the standard header and generate the precompiled header. +// + +#include "pch.h" +#include "MainPage.xaml.h" + +#include <robuffer.h> +#include <wrl\client.h> + +using namespace Microsoft::WRL; +using namespace Windows::Storage::Streams; + +byte* GetArrayFromBuffer(Windows::Storage::Streams::IBuffer^ buffer) +{ + ComPtr<IInspectable> base = reinterpret_cast<IInspectable*>(buffer); + ComPtr<IBufferByteAccess> access; + + auto hr = base.As(&access); + + if (FAILED(hr)) + { + throw Platform::Exception::CreateException(hr); + } + + byte* data; + + hr = access->Buffer(&data); + + if (FAILED(hr)) + { + throw Platform::Exception::CreateException(hr); + } + + // The returned buffer is valid as long as the IBuffer passed in + // remains valid. + return data; +} + +void NotifyStatusMessage(Platform::String^ message, SDKTemplate::NotifyType messageType) +{ + SDKTemplate::MainPage::Current->Dispatcher->RunAsync( + Windows::UI::Core::CoreDispatcherPriority::Normal, + ref new Windows::UI::Core::DispatchedHandler( + [message, messageType]() { + SDKTemplate::MainPage::Current->NotifyUser(message, messageType); + })); +} diff --git a/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/pch.h b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/pch.h new file mode 100644 index 00000000..3cec6ca5 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/App/CustomCapability/cpp/pch.h @@ -0,0 +1,27 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +// +// pch.h +// Header for standard system include files. +// + +#pragma once + +#include <collection.h> +#include <ppltasks.h> + +#include "App.xaml.h" +#include "MainPage.xaml.h" + +byte* GetArrayFromBuffer(Windows::Storage::Streams::IBuffer^ buffer); + +void NotifyStatusMessage(Platform::String^ message, SDKTemplate::NotifyType messageType); diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/App.xaml.cpp b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/App.xaml.cpp new file mode 100644 index 00000000..1abebcb3 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/App.xaml.cpp @@ -0,0 +1,134 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include "MainPage.xaml.h" + +using namespace SDKTemplate; + +using namespace Platform; +using namespace Windows::ApplicationModel; +using namespace Windows::ApplicationModel::Activation; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Controls; +using namespace Windows::UI::Xaml::Controls::Primitives; +using namespace Windows::UI::Xaml::Data; +using namespace Windows::UI::Xaml::Input; +using namespace Windows::UI::Xaml::Interop; +using namespace Windows::UI::Xaml::Media; +using namespace Windows::UI::Xaml::Navigation; + +// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409 + +// These placeholder functions are used if the sample does not +// implement the corresponding methods. This allows us to simulate +// C# partial methods in C++. + +static void Partial_Construct() { } + +/// <summary> +/// Initializes the singleton application object. This is the first line of authored code +/// executed, and as such is the logical equivalent of main() or WinMain(). +/// </summary> +App::App() +{ + InitializeComponent(); + Partial_Construct(); + Suspending += ref new Windows::UI::Xaml::SuspendingEventHandler(this, &SDKTemplate::App::OnSuspending); +} + +/// <summary> +/// Invoked when the application is launched normally by the end user. Other entry points +/// will be used such as when the application is launched to open a specific file. +/// </summary> +/// <param name="e">Details about the launch request and process.</param> +void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) +{ +#if _DEBUG + // Show graphics profiling information while debugging. + if (IsDebuggerPresent()) + { + // Display the current frame rate counters + DebugSettings->EnableFrameRateCounter = false; + } +#endif + + auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content); + + // Do not repeat app initialization when the Window already has content, + // just ensure that the window is active + if (rootFrame == nullptr) + { + // Create a Frame to act as the navigation context and associate it with + // a SuspensionManager key + rootFrame = ref new Frame(); + + // Set the default language + rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0); + + rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed); + + if (e->PreviousExecutionState == ApplicationExecutionState::Terminated) + { + // TODO: Restore the saved session state only when appropriate, scheduling the + // final launch steps after the restore is complete + } + + if (rootFrame->Content == nullptr) + { + // When the navigation stack isn't restored navigate to the first page, + // configuring the new page by passing required information as a navigation + // parameter + rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments); + } + // Place the frame in the current Window + Window::Current->Content = rootFrame; + // Ensure the current window is active + Window::Current->Activate(); + } + else + { + if (rootFrame->Content == nullptr) + { + // When the navigation stack isn't restored navigate to the first page, + // configuring the new page by passing required information as a navigation + // parameter + rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments); + } + // Ensure the current window is active + Window::Current->Activate(); + } +} + +/// <summary> +/// Invoked when application execution is being suspended. Application state is saved +/// without knowing whether the application will be terminated or resumed with the contents +/// of memory still intact. +/// </summary> +/// <param name="sender">The source of the suspend request.</param> +/// <param name="e">Details about the suspend request.</param> +void App::OnSuspending(Object^ /* sender */, SuspendingEventArgs^ /* e */) +{ + //TODO: Save application state and stop any background activity +} + + +/// <summary> +/// Invoked when Navigation to a certain page fails +/// </summary> +/// <param name="sender">The Frame which failed navigation</param> +/// <param name="e">Details about the navigation failure</param> +void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e) +{ + throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name); +}
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/App.xaml.h b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/App.xaml.h new file mode 100644 index 00000000..e7bd715a --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/App.xaml.h @@ -0,0 +1,33 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once + +#include "App.g.h" + +namespace SDKTemplate +{ + /// <summary> + /// Provides application-specific behavior to supplement the default Application class. + /// </summary> + ref class App sealed + { + protected: + virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override; + + internal: + App(); + + private: + void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e); + void OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e); + }; +} diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/DeviceHelpers.h b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/DeviceHelpers.h new file mode 100644 index 00000000..c2fa82b2 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/DeviceHelpers.h @@ -0,0 +1,67 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once + +namespace SDKTemplate +{ + namespace DeviceHelpers + { + // We use a DeviceWatcher instead of DeviceInformation.FindAllAsync because + // the DeviceWatcher will let us see the devices as they are discovered, + // whereas FindAllAsync returns results only after discovery is complete. + // + // The convertAsync functional is passed a device ID (Platform::String^) and returns a + // Concurrency::task<Something^>. + template<typename Converter> + auto GetFirstDeviceAsync(Platform::String^ selector, Converter convertAsync) + -> decltype(convertAsync(nullptr)) + { + using T = typename decltype(convertAsync(nullptr))::result_type; + Concurrency::task_completion_event<T> completionEvent; + auto pendingTasks = std::make_shared<std::vector<Concurrency::task<void>>>(); + Windows::Devices::Enumeration::DeviceWatcher^ watcher = Windows::Devices::Enumeration::DeviceInformation::CreateWatcher(selector); + + watcher->Added += ref new Windows::Foundation::TypedEventHandler<Windows::Devices::Enumeration::DeviceWatcher^, Windows::Devices::Enumeration::DeviceInformation^>( + [completionEvent, pendingTasks, convertAsync](Windows::Devices::Enumeration::DeviceWatcher^ sender, Windows::Devices::Enumeration::DeviceInformation^ device) + { + auto task = convertAsync(device->Id).then([completionEvent](T t) + { + if (t != nullptr) + { + completionEvent.set(t); + } + }); + pendingTasks->push_back(task); + }); + + watcher->EnumerationCompleted += ref new Windows::Foundation::TypedEventHandler<Windows::Devices::Enumeration::DeviceWatcher^, Platform::Object^>( + [completionEvent, pendingTasks](Windows::Devices::Enumeration::DeviceWatcher^ sender, Platform::Object^ args) + { + // Wait for completion of all the tasks we created in our "Added" event handler. + Concurrency::when_all(pendingTasks->begin(), pendingTasks->end()).then([completionEvent]() + { + // This sets the result to "nullptr" if no task was able to produce a device. + completionEvent.set(nullptr); + }); + }); + + watcher->Start(); + + // Wait for enumeration to complete or for a device to be found, whichever comes first. + return Concurrency::create_task(completionEvent).then([watcher](T result) + { + watcher->Stop(); + return result; + }); + } + } +} diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/MainPage.xaml b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/MainPage.xaml new file mode 100644 index 00000000..5179f520 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/MainPage.xaml @@ -0,0 +1,80 @@ +<!-- +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* +--> + +<Page + x:Class="SDKTemplate.MainPage" + xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + xmlns:local="using:SDKTemplate" + xmlns:d="http://schemas.microsoft.com/expression/blend/2008" + xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" + mc:Ignorable="d"> + + <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> + <Grid.RowDefinitions> + <RowDefinition Height="Auto"/> + <RowDefinition Height="*"/> + </Grid.RowDefinitions> + <SplitView x:Name="Splitter" IsPaneOpen="True" Grid.Row="1" DisplayMode="Inline"> + <SplitView.Pane> + <RelativePanel Margin="10,0,0,0"> + <TextBlock x:Name="SampleTitle" Text="Sample Title Here" Style="{StaticResource SampleHeaderTextStyle}" TextWrapping="Wrap" Margin="0,10,0,0"/> + <ListBox x:Name="ScenarioControl" SelectionChanged="ScenarioControl_SelectionChanged" + SelectionMode="Single" HorizontalAlignment="Left" Background="Transparent" BorderThickness="0" + VerticalAlignment="Top" RelativePanel.Below="SampleTitle" Margin="0,10,0,0" RelativePanel.Above="FooterPanel"> + <ListBox.ItemTemplate> + <DataTemplate> + <TextBlock Text="{Binding Converter={StaticResource ScenarioConverter}}"/> + </DataTemplate> + </ListBox.ItemTemplate> + </ListBox> + <StackPanel x:Name="FooterPanel" Orientation="Vertical" RelativePanel.AlignBottomWithPanel="True"> + <Image Source="Assets/microsoft-sdk.png" AutomationProperties.Name="Microsoft Logo" Stretch="None" HorizontalAlignment="Left" Margin="10,0,0,0"/> + <TextBlock x:Name="Copyright" Text="© Microsoft Corporation. All rights reserved." Style="{StaticResource CopyrightTextStyle}" + RelativePanel.Above="LinksPanel" Margin="10,10,0,0" + TextWrapping="Wrap"/> + <StackPanel x:Name="LinksPanel" Orientation="Horizontal" Margin="10,10,0,10"> + <HyperlinkButton Content="Trademarks" Tag="http://go.microsoft.com/fwlink/?LinkID=623755" + Click="Footer_Click" FontSize="12" Style="{StaticResource HyperlinkStyle}" /> + <TextBlock Text="|" Style="{StaticResource SeparatorStyle}" VerticalAlignment="Center" /> + <HyperlinkButton x:Name="PrivacyLink" Content="Privacy" Tag="http://privacy.microsoft.com" Click="Footer_Click" FontSize="12" Style="{StaticResource HyperlinkStyle}"/> + </StackPanel> + </StackPanel> + </RelativePanel> + </SplitView.Pane> + <RelativePanel> + <Frame x:Name="ScenarioFrame" Margin="0,5,0,0" RelativePanel.AlignTopWithPanel="True" RelativePanel.Above="StatusPanel" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True"/> + <StackPanel x:Name="StatusPanel" Orientation="Vertical" RelativePanel.AlignBottomWithPanel="True" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True"> + <TextBlock x:Name="StatusLabel" Margin="0,0,0,10" TextWrapping="Wrap" Text="Status:" /> + <Border x:Name="StatusBorder" Margin="0,0,0,0" Visibility="Visible" > + <ScrollViewer VerticalScrollMode="Auto" VerticalScrollBarVisibility="Auto" MaxHeight="200"> + <TextBlock x:Name="StatusBlock" FontWeight="Bold" + MaxWidth="{Binding ElementName=Splitter, Path=ActualWidth}" Margin="10,10,10,20" TextWrapping="Wrap" /> + </ScrollViewer> + </Border> + </StackPanel> + </RelativePanel> + </SplitView> + <StackPanel x:Name="HeaderPanel" Orientation="Horizontal"> + <Border Background="{ThemeResource SystemControlBackgroundChromeMediumBrush}" Grid.Row="0"> + <ToggleButton Style="{StaticResource SymbolButton}" Click="Button_Click" VerticalAlignment="Top" Foreground="{ThemeResource ApplicationForegroundThemeBrush}"> + <ToggleButton.Content> + <FontIcon x:Name="Hamburger" FontFamily="Segoe MDL2 Assets" Glyph="" Margin="0,10,0,0"/> + </ToggleButton.Content> + </ToggleButton> + </Border> + <Image x:Name="WindowsLogo" Stretch="None" Source="Assets/windows-sdk.png" Margin="0,15,0,0" /> + <TextBlock x:Name="Header" Text="Universal Windows Platform sample" Style="{StaticResource TagLineTextStyle}" Margin="0,15,0,0" /> + </StackPanel> + </Grid> +</Page> diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/MainPage.xaml.cpp b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/MainPage.xaml.cpp new file mode 100644 index 00000000..24c12f68 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/MainPage.xaml.cpp @@ -0,0 +1,154 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include "MainPage.xaml.h" + +using namespace SDKTemplate; +using namespace Platform; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; +using namespace Windows::UI::Core; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Controls; +using namespace Windows::UI::Xaml::Controls::Primitives; +using namespace Windows::UI::Xaml::Data; +using namespace Windows::UI::Xaml::Input; +using namespace Windows::UI::Xaml::Media; +using namespace Windows::UI::Xaml::Navigation; +using namespace Windows::UI::Xaml::Interop; + +// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 + +MainPage^ MainPage::Current = nullptr; + +MainPage::MainPage() +{ + InitializeComponent(); + SampleTitle->Text = FEATURE_NAME; + + // This is a static public property that allows downstream pages to get a handle to the MainPage instance + // in order to call methods that are in this class. + MainPage::Current = this; +} + +void MainPage::OnNavigatedTo(NavigationEventArgs^ e) +{ + // Populate the ListBox with the scenarios as defined in SampleConfiguration.cpp. + auto itemCollection = ref new Platform::Collections::Vector<Object^>(); + int i = 1; + for (auto const& s : MainPage::Current->scenarios) + { + // Create a textBlock to hold the content and apply the ListItemTextStyle from Styles.xaml + TextBlock^ textBlock = ref new TextBlock(); + ListBoxItem^ item = ref new ListBoxItem(); + auto style = App::Current->Resources->Lookup("ListItemTextStyle"); + + textBlock->Text = (i++).ToString() + ") " + s.Title; + textBlock->Style = safe_cast<Windows::UI::Xaml::Style ^>(style); + + item->Name = s.ClassName; + item->Content = textBlock; + itemCollection->Append(item); + } + + // Set the newly created itemCollection as the ListBox ItemSource. + ScenarioControl->ItemsSource = itemCollection; + int startingScenarioIndex; + + if (Window::Current->Bounds.Width < 640) + { + startingScenarioIndex = -1; + } + else + { + startingScenarioIndex = 0; + } + + ScenarioControl->SelectedIndex = startingScenarioIndex; + ScenarioControl->ScrollIntoView(ScenarioControl->SelectedItem); +} + + +void MainPage::ScenarioControl_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e) +{ + ListBox^ scenarioListBox = safe_cast<ListBox^>(sender); //as ListBox; + ListBoxItem^ item = dynamic_cast<ListBoxItem^>(scenarioListBox->SelectedItem); + if (item != nullptr) + { + // Clear the status block when changing scenarios + NotifyUser("", NotifyType::StatusMessage); + + // Navigate to the selected scenario. + TypeName scenarioType = { item->Name, TypeKind::Custom }; + ScenarioFrame->Navigate(scenarioType, this); + + if (Window::Current->Bounds.Width < 640) + { + Splitter->IsPaneOpen = false; + } + } +} + +void MainPage::NotifyUser(String^ strMessage, NotifyType type) +{ + if (Dispatcher->HasThreadAccess) + { + UpdateStatus(strMessage, type); + } + else + { + Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([strMessage, type, this]() + { + UpdateStatus(strMessage, type); + })); + } +} + +void MainPage::UpdateStatus(String^ strMessage, NotifyType type) +{ + switch (type) + { + case NotifyType::StatusMessage: + StatusBorder->Background = ref new SolidColorBrush(Windows::UI::Colors::Green); + break; + case NotifyType::ErrorMessage: + StatusBorder->Background = ref new SolidColorBrush(Windows::UI::Colors::Red); + break; + default: + break; + } + + StatusBlock->Text = strMessage; + + // Collapse the StatusBlock if it has no text to conserve real estate. + if (StatusBlock->Text != "") + { + StatusBorder->Visibility = Windows::UI::Xaml::Visibility::Visible; + StatusPanel->Visibility = Windows::UI::Xaml::Visibility::Visible; + } + else + { + StatusBorder->Visibility = Windows::UI::Xaml::Visibility::Collapsed; + StatusPanel->Visibility = Windows::UI::Xaml::Visibility::Collapsed; + } +} + +void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e) +{ + auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag); + Windows::System::Launcher::LaunchUriAsync(uri); +} + +void MainPage::Button_Click(Object^ sender, RoutedEventArgs^ e) +{ + Splitter->IsPaneOpen = !Splitter->IsPaneOpen; +}
\ No newline at end of file diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/MainPage.xaml.h b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/MainPage.xaml.h new file mode 100644 index 00000000..e87e24f0 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/cpp/MainPage.xaml.h @@ -0,0 +1,46 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once + +#include "MainPage.g.h" +#include "SampleConfiguration.h" + +namespace SDKTemplate +{ + public enum class NotifyType + { + StatusMessage, + ErrorMessage + }; + + /// <summary> + /// An empty page that can be used on its own or navigated to within a Frame. + /// </summary> + public ref class MainPage sealed + { + public: + MainPage(); + + protected: + virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override; + + private: + void ScenarioControl_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e); + void Footer_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); + void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); + void UpdateStatus(Platform::String^ strMessage, NotifyType type); + + internal: + static MainPage^ Current; + void NotifyUser(Platform::String^ strMessage, NotifyType type); + }; +} diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/Square310x310Logo.png b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/Square310x310Logo.png Binary files differnew file mode 100644 index 00000000..c96f294a --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/Square310x310Logo.png diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/microsoft-sdk.png b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/microsoft-sdk.png Binary files differnew file mode 100644 index 00000000..380a0102 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/microsoft-sdk.png diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/placeholder-sdk.png b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/placeholder-sdk.png Binary files differnew file mode 100644 index 00000000..01b3138c --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/placeholder-sdk.png diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/placeholder.png b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/placeholder.png Binary files differnew file mode 100644 index 00000000..e2d83818 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/placeholder.png diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/smalltile-sdk.png b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/smalltile-sdk.png Binary files differnew file mode 100644 index 00000000..ba9a0cde --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/smalltile-sdk.png diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/splash-sdk.png b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/splash-sdk.png Binary files differnew file mode 100644 index 00000000..e00df02c --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/splash-sdk.png diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/squaretile-sdk.png b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/squaretile-sdk.png Binary files differnew file mode 100644 index 00000000..f97c34a9 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/squaretile-sdk.png diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/storelogo-sdk.png b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/storelogo-sdk.png Binary files differnew file mode 100644 index 00000000..5c397dea --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/storelogo-sdk.png diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/tile-sdk.png b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/tile-sdk.png Binary files differnew file mode 100644 index 00000000..f72683f2 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/tile-sdk.png diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/windows-sdk.png b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/windows-sdk.png Binary files differnew file mode 100644 index 00000000..67268021 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/media/windows-sdk.png diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/xaml/App.xaml b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/xaml/App.xaml new file mode 100644 index 00000000..63e80b83 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/xaml/App.xaml @@ -0,0 +1,34 @@ +<!-- +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* +--> +<Application + x:Class="SDKTemplate.App" + xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + xmlns:local="using:SDKTemplate" + RequestedTheme="Dark"> + + <Application.Resources> + <!-- Application-specific resources --> + <ResourceDictionary> + <ResourceDictionary.MergedDictionaries> + + <!-- + Styles that define common aspects of the platform look and feel + Required by Visual Studio project and item templates + --> + <ResourceDictionary Source="/Styles/Styles.xaml"/> + </ResourceDictionary.MergedDictionaries> + </ResourceDictionary> + </Application.Resources> + +</Application> diff --git a/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/xaml/Styles.xaml b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/xaml/Styles.xaml new file mode 100644 index 00000000..50602ae5 --- /dev/null +++ b/general/WinHEC 2017 Lab/Toaster Support App/SharedContent/xaml/Styles.xaml @@ -0,0 +1,536 @@ +<!-- +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* +--> +<ResourceDictionary + xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + xmlns:local="using:SDKTemplate"> + + <Style x:Key="SymbolButton" TargetType="ToggleButton"> + <Setter Property="FontSize" Value="16" /> + <Setter Property="FontFamily" Value="{StaticResource SymbolThemeFontFamily}" /> + <Setter Property="MinHeight" Value="48" /> + <Setter Property="MinWidth" Value="48" /> + <Setter Property="Margin" Value="0,4,0,0" /> + <Setter Property="Padding" Value="0" /> + <Setter Property="HorizontalAlignment" Value="Left" /> + <Setter Property="VerticalAlignment" Value="Top" /> + <Setter Property="HorizontalContentAlignment" Value="Center" /> + <Setter Property="VerticalContentAlignment" Value="Center" /> + <Setter Property="Background" Value="Transparent" /> + <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}" /> + <Setter Property="Content" Value="" /> + <Setter Property="AutomationProperties.Name" Value="Menu" /> + <Setter Property="UseSystemFocusVisuals" Value="True" /> + <Setter Property="Template"> + <Setter.Value> + <ControlTemplate TargetType="ToggleButton"> + <Grid x:Name="LayoutRoot" + Background="{TemplateBinding Background}"> + <VisualStateManager.VisualStateGroups> + <VisualStateGroup x:Name="CommonStates"> + <VisualState x:Name="Normal" /> + <VisualState x:Name="PointerOver"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(Grid.Background)"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightListLowBrush}"/> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltBaseHighBrush}"/> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="Pressed"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(Grid.Background)"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightListMediumBrush}"/> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltBaseHighBrush}"/> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="Disabled"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="(TextBlock.Foreground)"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="Checked"/> + <VisualState x:Name="CheckedPointerOver"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(Grid.Background)"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightListLowBrush}"/> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltBaseHighBrush}"/> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="CheckedPressed"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(Grid.Background)"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightListMediumBrush}"/> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltBaseHighBrush}"/> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="CheckedDisabled"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="(TextBlock.Foreground)"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + </VisualStateGroup> + </VisualStateManager.VisualStateGroups> + <ContentPresenter x:Name="ContentPresenter" + Content="{TemplateBinding Content}" + Margin="{TemplateBinding Padding}" + HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" + VerticalAlignment="{TemplateBinding VerticalContentAlignment}" + AutomationProperties.AccessibilityView="Raw" /> + </Grid> + </ControlTemplate> + </Setter.Value> + </Setter> + </Style> + + <Style x:Key="BasicTextStyle" TargetType="TextBlock" BasedOn="{StaticResource BodyTextBlockStyle}"> + <Setter Property="Margin" Value="0,0,0,12"/> + </Style> + + <Style x:Key="TagLineTextStyle" TargetType="TextBlock" BasedOn="{StaticResource BodyTextBlockStyle}"> + </Style> + + <Style x:Key="SampleHeaderTextStyle" TargetType="TextBlock" BasedOn="{StaticResource TitleTextBlockStyle}"> + <Setter Property="FontSize" Value="28"/> + </Style> + + <Style x:Key="ListItemTextStyle" TargetType="TextBlock" BasedOn="{StaticResource SubtitleTextBlockStyle}"> + <Setter Property="FontSize" Value="18"/> + <Setter Property="Margin" Value="10,0,0,0"/> + <Setter Property="Foreground" Value="{StaticResource SystemControlForegroundBaseHighBrush}"/> + </Style> + + <Style x:Key="CopyrightTextStyle" TargetType="TextBlock" BasedOn="{StaticResource BaseTextBlockStyle}"> + <Setter Property="FontWeight" Value="Normal"/> + </Style> + + <Style x:Key="ScenarioHeaderTextStyle" TargetType="TextBlock" BasedOn="{StaticResource TitleTextBlockStyle}"> + </Style> + + <Style x:Key="ScenarioDescriptionTextStyle" TargetType="TextBlock" BasedOn="{StaticResource BodyTextBlockStyle}"> + </Style> + + <Style x:Key="BaseMessageStyle" TargetType="TextBlock" BasedOn="{StaticResource BodyTextBlockStyle}"> + <Setter Property="Margin" Value="0,0,0,5"/> + </Style> + + <Style x:Key="SeparatorStyle" TargetType="TextBlock" BasedOn="{StaticResource BaseTextBlockStyle}"> + <Setter Property="FontSize" Value="9"/> + <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseMediumBrush}"/> + </Style> + + <Style x:Key="HyperlinkStyle" TargetType="HyperlinkButton"> + <Setter Property="Padding" Value="1"/> + <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseMediumBrush}"/> + <Setter Property="FontSize" Value="12"/> + </Style> + + <Style x:Key="NavMenuItemContainerStyle" TargetType="ListViewItem"> + <Setter Property="MinWidth" Value="{StaticResource SplitViewCompactPaneThemeLength}"/> + <Setter Property="MinHeight" Value="48"/> + <Setter Property="Padding" Value="0"/> + <Setter Property="UseSystemFocusVisuals" Value="False" /> + <Setter Property="Template"> + <Setter.Value> + <ControlTemplate TargetType="ListViewItem"> + <Grid x:Name="ContentBorder" + HorizontalAlignment="Stretch" + Control.IsTemplateFocusTarget="True" + Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" + BorderThickness="{TemplateBinding BorderThickness}" + RenderTransformOrigin="0.5,0.5"> + <Grid.RenderTransform> + <ScaleTransform x:Name="ContentBorderScale" /> + </Grid.RenderTransform> + <VisualStateManager.VisualStateGroups> + <VisualStateGroup x:Name="CommonStates"> + <VisualState x:Name="Normal"> + <Storyboard> + <PointerUpThemeAnimation Storyboard.TargetName="ContentPresenter" /> + </Storyboard> + </VisualState> + <VisualState x:Name="PointerOver"> + <Storyboard> + <DoubleAnimation Storyboard.TargetName="BorderBackground" + Storyboard.TargetProperty="Opacity" + Duration="0" + To="1"/> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderBackground" Storyboard.TargetProperty="Fill"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightListLowBrush}" /> + </ObjectAnimationUsingKeyFrames> + <PointerUpThemeAnimation Storyboard.TargetName="ContentPresenter" /> + </Storyboard> + </VisualState> + <VisualState x:Name="Pressed"> + <Storyboard> + <DoubleAnimation Storyboard.TargetName="BorderBackground" + Storyboard.TargetProperty="Opacity" + Duration="0" + To="1"/> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderBackground" Storyboard.TargetProperty="Fill"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightListMediumBrush}" /> + </ObjectAnimationUsingKeyFrames> + <PointerDownThemeAnimation TargetName="ContentPresenter" /> + </Storyboard> + </VisualState> + <VisualState x:Name="Selected"> + <Storyboard> + <DoubleAnimation Storyboard.TargetName="BorderBackground" + Storyboard.TargetProperty="Opacity" + Duration="0" + To="1"/> + <DoubleAnimation Storyboard.TargetName="SelectedPipe" + Storyboard.TargetProperty="Opacity" + Duration="0" + To="1"/> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderBackground" Storyboard.TargetProperty="Fill"> + <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent" /> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlForegroundAccentBrush}" /> + </ObjectAnimationUsingKeyFrames> + <PointerUpThemeAnimation Storyboard.TargetName="ContentPresenter" /> + </Storyboard> + </VisualState> + <VisualState x:Name="PointerOverSelected"> + <Storyboard> + <DoubleAnimation Storyboard.TargetName="BorderBackground" + Storyboard.TargetProperty="Opacity" + Duration="0" + To="1"/> + <DoubleAnimation Storyboard.TargetName="SelectedPipe" + Storyboard.TargetProperty="Opacity" + Duration="0" + To="1"/> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderBackground" Storyboard.TargetProperty="Fill"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightListLowBrush}" /> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlForegroundAccentBrush}" /> + </ObjectAnimationUsingKeyFrames> + <PointerUpThemeAnimation Storyboard.TargetName="ContentPresenter" /> + </Storyboard> + </VisualState> + <VisualState x:Name="PressedSelected"> + <Storyboard> + <DoubleAnimation Storyboard.TargetName="BorderBackground" + Storyboard.TargetProperty="Opacity" + Duration="0" + To="1"/> + <DoubleAnimation Storyboard.TargetName="SelectedPipe" + Storyboard.TargetProperty="Opacity" + Duration="0" + To="1"/> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderBackground" Storyboard.TargetProperty="Fill"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightListMediumBrush}" /> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlForegroundAccentBrush}" /> + </ObjectAnimationUsingKeyFrames> + <PointerDownThemeAnimation TargetName="ContentPresenter" /> + </Storyboard> + </VisualState> + </VisualStateGroup> + <VisualStateGroup x:Name="DisabledStates"> + <VisualState x:Name="Enabled"/> + <VisualState x:Name="Disabled"> + <Storyboard> + <DoubleAnimation Storyboard.TargetName="ContentBorder" + Storyboard.TargetProperty="Opacity" + Duration="0" + To="{ThemeResource ListViewItemDisabledThemeOpacity}"/> + </Storyboard> + </VisualState> + </VisualStateGroup> + <VisualStateGroup x:Name="FocusStates"> + <VisualState x:Name="Unfocused"/> + <VisualState x:Name="Focused"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="FocusBackground" Storyboard.TargetProperty="Fill"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightListLowBrush}" /> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + </VisualStateGroup> + </VisualStateManager.VisualStateGroups> + <Rectangle x:Name="BorderBackground" + IsHitTestVisible="False" + Fill="Transparent" + Opacity="1" + Control.IsTemplateFocusTarget="True" /> + <Rectangle x:Name="FocusBackground" + IsHitTestVisible="False" + Fill="Transparent" + Opacity="1" + Control.IsTemplateFocusTarget="True"/> + <Rectangle x:Name="SelectedPipe" + Opacity="0" + Width="4" + Height="24" + Fill="{ThemeResource SystemControlForegroundAccentBrush}" + VerticalAlignment="Center" + HorizontalAlignment="Left"/> + <ContentPresenter x:Name="ContentPresenter" + ContentTransitions="{TemplateBinding ContentTransitions}" + ContentTemplate="{TemplateBinding ContentTemplate}" + Content="{TemplateBinding Content}" + HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" + VerticalAlignment="{TemplateBinding VerticalContentAlignment}" + Margin="16,0,0,0" /> + </Grid> + </ControlTemplate> + </Setter.Value> + </Setter> + </Style> + + <!-- Default style for Windows.UI.Xaml.Controls.ListBoxItem --> + <Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem"> + <Setter Property="Background" Value="Transparent" /> + <Setter Property="TabNavigation" Value="Local" /> + <Setter Property="Padding" Value="8,10" /> + <Setter Property="HorizontalContentAlignment" Value="Left" /> + <Setter Property="Template"> + <Setter.Value> + <ControlTemplate TargetType="ListBoxItem"> + <Border x:Name="LayoutRoot" + Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" + BorderThickness="{TemplateBinding BorderThickness}"> + <VisualStateManager.VisualStateGroups> + <VisualStateGroup x:Name="CommonStates"> + <VisualState x:Name="Normal" /> + <VisualState x:Name="PointerOver"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="LayoutRoot" + Storyboard.TargetProperty="Background"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemPointerOverBackgroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" + Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemPointerOverForegroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="Disabled"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="LayoutRoot" + Storyboard.TargetProperty="Background"> + <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent" /> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" + Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemDisabledForegroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="Pressed"> + <Storyboard> + <DoubleAnimation Storyboard.TargetName="PressedBackground" + Storyboard.TargetProperty="Opacity" + To="1" + Duration="0" /> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" + Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemPressedForegroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + </VisualStateGroup> + <VisualStateGroup x:Name="SelectionStates"> + <VisualState x:Name="Unselected" /> + <VisualState x:Name="Selected"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="InnerGrid" + Storyboard.TargetProperty="Background"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemSelectedBackgroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" + Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemSelectedForegroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="SelectedUnfocused"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="InnerGrid" + Storyboard.TargetProperty="Background"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemSelectedBackgroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" + Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemSelectedForegroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="SelectedDisabled"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="InnerGrid" + Storyboard.TargetProperty="Background"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemSelectedDisabledBackgroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" + Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemSelectedDisabledForegroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="SelectedPointerOver"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="InnerGrid" + Storyboard.TargetProperty="Background"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemSelectedPointerOverBackgroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" + Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemSelectedForegroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="SelectedPressed"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="InnerGrid" + Storyboard.TargetProperty="Background"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemSelectedBackgroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" + Storyboard.TargetProperty="Foreground"> + <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ListBoxItemSelectedForegroundThemeBrush}" /> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + </VisualStateGroup> + <VisualStateGroup x:Name="FocusStates"> + <VisualState x:Name="Focused"> + <Storyboard> + <DoubleAnimation Storyboard.TargetName="FocusVisualWhite" + Storyboard.TargetProperty="Opacity" + To="1" + Duration="0" /> + <DoubleAnimation Storyboard.TargetName="FocusVisualBlack" + Storyboard.TargetProperty="Opacity" + To="1" + Duration="0" /> + </Storyboard> + </VisualState> + <VisualState x:Name="Unfocused" /> + <VisualState x:Name="PointerFocused" /> + </VisualStateGroup> + </VisualStateManager.VisualStateGroups> + <Grid x:Name="InnerGrid" + Background="Transparent"> + <Rectangle x:Name="PressedBackground" + Fill="{ThemeResource ListBoxItemPressedBackgroundThemeBrush}" + Opacity="0" /> + <ContentPresenter x:Name="ContentPresenter" + Content="{TemplateBinding Content}" + ContentTransitions="{TemplateBinding ContentTransitions}" + ContentTemplate="{TemplateBinding ContentTemplate}" + HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" + VerticalAlignment="{TemplateBinding VerticalContentAlignment}" + Margin="{TemplateBinding Padding}" /> + <Rectangle x:Name="FocusVisualWhite" + Stroke="{ThemeResource FocusVisualWhiteStrokeThemeBrush}" + StrokeEndLineCap="Square" + StrokeDashArray="1,1" + Opacity="0" + StrokeDashOffset=".5" /> + <Rectangle x:Name="FocusVisualBlack" + Stroke="{ThemeResource FocusVisualBlackStrokeThemeBrush}" + StrokeEndLineCap="Square" + StrokeDashArray="1,1" + Opacity="0" + StrokeDashOffset="1.5" /> + </Grid> + </Border> + </ControlTemplate> + </Setter.Value> + </Setter> + </Style> + + <Style x:Key="ScenarioListBoxStyle" TargetType="ListBox"> + <Setter Property="Foreground" Value="{ThemeResource ListBoxForegroundThemeBrush}"/> + <Setter Property="Background" Value="Transparent"/> + <Setter Property="BorderBrush" Value="Transparent"/> + <Setter Property="BorderThickness" Value="{ThemeResource ListBoxBorderThemeThickness}"/> + <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/> + <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/> + <Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled"/> + <Setter Property="ScrollViewer.IsHorizontalRailEnabled" Value="True"/> + <Setter Property="ScrollViewer.VerticalScrollMode" Value="Enabled"/> + <Setter Property="ScrollViewer.IsVerticalRailEnabled" Value="True"/> + <Setter Property="ScrollViewer.ZoomMode" Value="Disabled"/> + <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/> + <Setter Property="ScrollViewer.BringIntoViewOnFocusChange" Value="True"/> + <Setter Property="IsTabStop" Value="False"/> + <Setter Property="TabNavigation" Value="Once"/> + <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/> + <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/> + <Setter Property="ItemsPanel"> + <Setter.Value> + <ItemsPanelTemplate> + <VirtualizingStackPanel Background="Transparent"/> + </ItemsPanelTemplate> + </Setter.Value> + </Setter> + <Setter Property="Template"> + <Setter.Value> + <ControlTemplate TargetType="ListBox"> + <Border x:Name="LayoutRoot" BorderBrush="Transparent" BorderThickness="{TemplateBinding BorderThickness}" Background="Transparent"> + <VisualStateManager.VisualStateGroups> + <VisualStateGroup x:Name="CommonStates"> + <VisualState x:Name="Normal"/> + <VisualState x:Name="Disabled"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="LayoutRoot"> + <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + </VisualStateGroup> + <VisualStateGroup x:Name="FocusStates"> + <VisualState x:Name="Focused"> + <Storyboard> + <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="LayoutRoot"> + <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/> + </ObjectAnimationUsingKeyFrames> + </Storyboard> + </VisualState> + <VisualState x:Name="Unfocused"/> + </VisualStateGroup> + </VisualStateManager.VisualStateGroups> + <ScrollViewer x:Name="ScrollViewer" AutomationProperties.AccessibilityView="Raw" BringIntoViewOnFocusChange="{TemplateBinding ScrollViewer.BringIntoViewOnFocusChange}" HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}" HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}" IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}" IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}" IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}" Padding="{TemplateBinding Padding}" TabNavigation="{TemplateBinding TabNavigation}" VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}" VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}" ZoomMode="{TemplateBinding ScrollViewer.ZoomMode}"> + <ItemsPresenter/> + </ScrollViewer> + </Border> + </ControlTemplate> + </Setter.Value> + </Setter> + </Style> + +</ResourceDictionary> diff --git a/general/WinHEC 2017 Lab/WinHEC 2017 Lab.docx b/general/WinHEC 2017 Lab/WinHEC 2017 Lab.docx Binary files differnew file mode 100644 index 00000000..62d0454f --- /dev/null +++ b/general/WinHEC 2017 Lab/WinHEC 2017 Lab.docx diff --git a/general/WinHEC 2017 Lab/WinHEC 2017 Lab.zip b/general/WinHEC 2017 Lab/WinHEC 2017 Lab.zip Binary files differnew file mode 100644 index 00000000..b2fb8ae2 --- /dev/null +++ b/general/WinHEC 2017 Lab/WinHEC 2017 Lab.zip diff --git a/general/cancel/README.md b/general/cancel/README.md index 2a1be648..491ef673 100644 --- a/general/cancel/README.md +++ b/general/cancel/README.md @@ -1,3 +1,13 @@ +<!--- + name: Cancel-Safe IRP Queue Sample + platform: WDM + language: cpp + category: General + description: Demonstrates the use of the cancel-safe queue routines. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617705 +---> + + Cancel-Safe IRP Queue Sample ============================ diff --git a/general/echo/kmdf/README.md b/general/echo/kmdf/README.md index 3b89850c..2ed4518a 100644 --- a/general/echo/kmdf/README.md +++ b/general/echo/kmdf/README.md @@ -1,3 +1,13 @@ +<!--- + name: KMDF Echo Sample + platform: KMDF + language: cpp + category: General WDF + description: Demonstrates how to use a sequential queue to serialize read and write requests presented to the driver. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617706 +---> + + KMDF Echo Sample ================ diff --git a/general/echo/kmdf/driver/AutoSync/echo.inx b/general/echo/kmdf/driver/AutoSync/echo.inx Binary files differindex d22c8806..bfb3b356 100644 --- a/general/echo/kmdf/driver/AutoSync/echo.inx +++ b/general/echo/kmdf/driver/AutoSync/echo.inx diff --git a/general/echo/kmdf/driver/AutoSync/echo.vcxproj b/general/echo/kmdf/driver/AutoSync/echo.vcxproj index b41d49c9..ee243a5d 100644 --- a/general/echo/kmdf/driver/AutoSync/echo.vcxproj +++ b/general/echo/kmdf/driver/AutoSync/echo.vcxproj @@ -146,7 +146,7 @@ <ClCompile Include="queue.c" /> </ItemGroup> <ItemGroup> - <Inf Exclude="@(Inf)" Include="*.inf" /> + <Inf Exclude="@(Inf)" Include="*.inx" /> <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'" /> </ItemGroup> <ItemGroup> @@ -158,4 +158,4 @@ <ClInclude Exclude="@(ClInclude)" Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd" /> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> -</Project>
\ No newline at end of file +</Project> diff --git a/general/echo/kmdf/driver/AutoSync/queue.c b/general/echo/kmdf/driver/AutoSync/queue.c index b821add2..d881c003 100644 --- a/general/echo/kmdf/driver/AutoSync/queue.c +++ b/general/echo/kmdf/driver/AutoSync/queue.c @@ -86,7 +86,7 @@ Return Value: // with the same lock. // queueAttributes.SynchronizationScope = WdfSynchronizationScopeQueue; - + queueAttributes.EvtDestroyCallback = EchoEvtIoQueueContextDestroy; status = WdfIoQueueCreate( @@ -155,12 +155,12 @@ Return Value: PAGED_CODE(); // - // Create a WDFTIMER object + // Create a periodic timer. + // + // WDF_TIMER_CONFIG_INIT_PERIODIC sets AutomaticSerialization to TRUE by default. // WDF_TIMER_CONFIG_INIT_PERIODIC(&timerConfig, EchoEvtTimerFunc, Period); - timerConfig.AutomaticSerialization = FALSE; - WDF_OBJECT_ATTRIBUTES_INIT(&timerAttributes); timerAttributes.ParentObject = Queue; // Synchronize with the I/O Queue diff --git a/general/echo/kmdf/driver/DriverSync/device.c b/general/echo/kmdf/driver/DriverSync/device.c index c9dbcbb4..23f684e9 100644 --- a/general/echo/kmdf/driver/DriverSync/device.c +++ b/general/echo/kmdf/driver/DriverSync/device.c @@ -77,17 +77,6 @@ Return Value: WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, DEVICE_CONTEXT); - // - // By not setting the synchronization scope and using the default, there is - // no locking between any of the callbacks in this driver. - // - // We will create a sequential queue so all of the EvtIoXxx callbacks are - // serialized against each other (at least until the request is completed), - // but the cancel routine and the timer DPC are not synchronized against the - // queue's EvtIoXxx callbacks. - // - // attributes.SynchronizationScope = ... - status = WdfDeviceCreate(&DeviceInit, &attributes, &device); if (NT_SUCCESS(status)) { diff --git a/general/echo/kmdf/driver/DriverSync/echo_2.inx b/general/echo/kmdf/driver/DriverSync/echo_2.inx Binary files differindex 235d12c0..ea524f85 100644 --- a/general/echo/kmdf/driver/DriverSync/echo_2.inx +++ b/general/echo/kmdf/driver/DriverSync/echo_2.inx diff --git a/general/echo/kmdf/driver/DriverSync/echo_2.vcxproj b/general/echo/kmdf/driver/DriverSync/echo_2.vcxproj index 95957fec..4a77818d 100644 --- a/general/echo/kmdf/driver/DriverSync/echo_2.vcxproj +++ b/general/echo/kmdf/driver/DriverSync/echo_2.vcxproj @@ -158,7 +158,7 @@ <ClCompile Include="queue.c" /> </ItemGroup> <ItemGroup> - <Inf Exclude="@(Inf)" Include="*.inf" /> + <Inf Exclude="@(Inf)" Include="*.inx" /> <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'" /> </ItemGroup> <ItemGroup> diff --git a/general/echo/kmdf/driver/DriverSync/queue.c b/general/echo/kmdf/driver/DriverSync/queue.c index 78c199d2..7835b73b 100644 --- a/general/echo/kmdf/driver/DriverSync/queue.c +++ b/general/echo/kmdf/driver/DriverSync/queue.c @@ -158,6 +158,18 @@ Return Value: // Fill in a callback for destroy, and our QUEUE_CONTEXT size // WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, QUEUE_CONTEXT); + + // + // By not setting the synchronization scope and using the default, there is + // no locking between any of the callbacks in this driver. + // + // We will create a sequential queue so all of the EvtIoXxx callbacks are + // serialized against each other (at least until the request is completed), + // but the cancel routine and the timer DPC are not synchronized against the + // queue's EvtIoXxx callbacks. + // + // attributes.SynchronizationScope = ... + attributes.EvtDestroyCallback = EchoEvtIoQueueContextDestroy; status = WdfIoQueueCreate( @@ -192,7 +204,7 @@ Return Value: KdPrint(("WdfSpinLockCreate failed 0x%x\n",status)); return status; } - + // // Create the Queue timer // @@ -234,16 +246,15 @@ Return Value: PAGED_CODE(); // - // Create a WDFTIMER object + // Create a periodic timer. + // + // By not setting the synchronization scope and using the default at WdfIoQueueCreate, + // we are explicitly *not* serializing against the queue's lock. Instead, we will do + // that on our own. // WDF_TIMER_CONFIG_INIT_PERIODIC(&timerConfig, EchoEvtTimerFunc, Period); WDF_OBJECT_ATTRIBUTES_INIT(&timerAttributes); - - // - // We are explicitly *not* serializing against the queue's lock, we will do - // that on our own. - // timerAttributes.ParentObject = Queue; Status = WdfTimerCreate( @@ -456,9 +467,9 @@ EchoSetCurrentRequest( queueContext->CurrentStatus = STATUS_SUCCESS; // - // Set the cancel routine under the lock, otherwise if we set it outside - // of the lock, the timer could run and attempt to mark the request - // uncancelable before we can mark it cancelable on this thread. Use + // Set the cancel routine under the lock, otherwise if we set it outside + // of the lock, the timer could run and attempt to mark the request + // uncancelable before we can mark it cancelable on this thread. Use // WdfRequestMarkCancelableEx here to prevent to deadlock with ourselves // (cancel routine tries to acquire the queue object lock). // @@ -746,7 +757,7 @@ Return Value: // } } - + WdfSpinLockRelease(queueContext->SpinLock); // diff --git a/general/echo/umdf/README.md b/general/echo/umdf/README.md index e2123cd3..af4818d4 100644 --- a/general/echo/umdf/README.md +++ b/general/echo/umdf/README.md @@ -1,3 +1,13 @@ +<!--- + name: Echo Sample (UMDF Version 1) + platform: UMDF1 + language: cpp + category: General WDF + description: Demonstrates how to use UMDF version 1 to write a driver and demonstrates best practices. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617707 +---> + + Echo Sample (UMDF Version 1) ============================ diff --git a/general/echo/umdf/WUDFEchoDriver.vcxproj b/general/echo/umdf/WUDFEchoDriver.vcxproj index c9a5a638..b00330bf 100644 --- a/general/echo/umdf/WUDFEchoDriver.vcxproj +++ b/general/echo/umdf/WUDFEchoDriver.vcxproj @@ -235,7 +235,7 @@ <ResourceCompile Include="Echo.rc" /> </ItemGroup> <ItemGroup> - <Inf Exclude="@(Inf)" Include="*.inf" /> + <Inf Exclude="@(Inf)" Include="*.inx" /> <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'" /> </ItemGroup> <ItemGroup> diff --git a/general/echo/umdf2/README.md b/general/echo/umdf2/README.md index ba3ffa36..a9ec9e76 100644 --- a/general/echo/umdf2/README.md +++ b/general/echo/umdf2/README.md @@ -1,3 +1,12 @@ +<!--- + name: Echo Sample (UMDF Version 2) + platform: UMDF2 + language: cpp + category: General WDF + description: Demonstrates how to use UMDF 2 to write a driver and to employ best practices. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617708 +---> + Echo Sample (UMDF Version 2) ============================ diff --git a/general/echo/umdf2/driver/AutoSync/echo.vcxproj b/general/echo/umdf2/driver/AutoSync/echo.vcxproj index e3a2e18d..17763154 100644 --- a/general/echo/umdf2/driver/AutoSync/echo.vcxproj +++ b/general/echo/umdf2/driver/AutoSync/echo.vcxproj @@ -158,7 +158,7 @@ <ClCompile Include="queue.c" /> </ItemGroup> <ItemGroup> - <Inf Exclude="@(Inf)" Include="*.inf" /> + <Inf Exclude="@(Inf)" Include="*.inx" /> <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'" /> </ItemGroup> <ItemGroup> diff --git a/general/echo/umdf2/driver/AutoSync/echoum.inx b/general/echo/umdf2/driver/AutoSync/echoum.inx Binary files differindex 4e3cd6b3..cae8b45f 100644 --- a/general/echo/umdf2/driver/AutoSync/echoum.inx +++ b/general/echo/umdf2/driver/AutoSync/echoum.inx diff --git a/general/echo/umdf2/driver/AutoSync/queue.c b/general/echo/umdf2/driver/AutoSync/queue.c index 3162a683..98860df6 100644 --- a/general/echo/umdf2/driver/AutoSync/queue.c +++ b/general/echo/umdf2/driver/AutoSync/queue.c @@ -79,7 +79,7 @@ Return Value: // with the same lock. // queueAttributes.SynchronizationScope = WdfSynchronizationScopeQueue; - + queueAttributes.EvtDestroyCallback = EchoEvtIoQueueContextDestroy; status = WdfIoQueueCreate( @@ -145,21 +145,18 @@ Return Value: WDF_OBJECT_ATTRIBUTES timerAttributes; // - // Create a WDFTIMER object + // Create a non-periodic timer since WDF does not allow periodic timer + // at passive level, which is the level UMDF callbacks are invoked at. + // The workaround is to always restart the timer in the timer callback. + // + // WDF_TIMER_CONFIG_INIT sets AutomaticSerialization to TRUE by default. // WDF_TIMER_CONFIG_INIT(&timerConfig, EchoEvtTimerFunc); - // - // WDF_OBJECT_ATTRIBUTES_INIT sets AutomaticSerialization to TRUE by default - // WDF_OBJECT_ATTRIBUTES_INIT(&timerAttributes); timerAttributes.ParentObject = Queue; // Synchronize with the I/O Queue - timerAttributes.ExecutionLevel = WdfExecutionLevelPassive; + timerAttributes.ExecutionLevel = WdfExecutionLevelPassive; - // - // Create a non-periodic timer since WDF does not allow periodic timer - // with autosynchronization at passive level - // Status = WdfTimerCreate(&timerConfig, &timerAttributes, Timer // Output handle @@ -530,7 +527,7 @@ Return Value: } // - // Restart the Timer since WDF does not allow periodic timer + // Restart the Timer since WDF does not allow periodic timer // with autosynchronization at passive level // WdfTimerStart(Timer, WDF_REL_TIMEOUT_IN_MS(TIMER_PERIOD)); diff --git a/general/echo/umdfSocketEcho/Driver/SocketEcho.inx b/general/echo/umdfSocketEcho/Driver/SocketEcho.inx Binary files differindex b80dee9a..b660186b 100644 --- a/general/echo/umdfSocketEcho/Driver/SocketEcho.inx +++ b/general/echo/umdfSocketEcho/Driver/SocketEcho.inx diff --git a/general/echo/umdfSocketEcho/Driver/SocketEcho.vcxproj b/general/echo/umdfSocketEcho/Driver/SocketEcho.vcxproj index 750422be..14a05def 100644 --- a/general/echo/umdfSocketEcho/Driver/SocketEcho.vcxproj +++ b/general/echo/umdfSocketEcho/Driver/SocketEcho.vcxproj @@ -224,7 +224,7 @@ <ResourceCompile Include="SocketEcho.rc" /> </ItemGroup> <ItemGroup> - <Inf Exclude="@(Inf)" Include="*.inf" /> + <Inf Exclude="@(Inf)" Include="*.inx" /> <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'" /> </ItemGroup> <ItemGroup> diff --git a/general/echo/umdfSocketEcho/README.md b/general/echo/umdfSocketEcho/README.md index 06819a47..26cd5a7e 100644 --- a/general/echo/umdfSocketEcho/README.md +++ b/general/echo/umdfSocketEcho/README.md @@ -1,3 +1,13 @@ +<!--- + name: UMDF SocketEcho Sample (UMDF Version 1) + platform: UMDF1 + language: cpp + category: General WDF + description: Demonstrates how to use UMDF version 1 to write a driver and demonstrates best practices. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617709 +---> + + UMDF SocketEcho Sample (UMDF Version 1) ======================================= diff --git a/general/event/README.md b/general/event/README.md index c091af5a..68da1666 100644 --- a/general/event/README.md +++ b/general/event/README.md @@ -1,3 +1,13 @@ +<!--- + name: Hardware Event Sample + platform: WDM + language: cpp + category: General + description: Demonstrates different ways a kernel-mode driver can notify an application about a hardware event. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617711 +---> + + Hardware Event Sample ===================== diff --git a/general/filehistory/README.md b/general/filehistory/README.md index 3e29b08e..7ed723d8 100644 --- a/general/filehistory/README.md +++ b/general/filehistory/README.md @@ -1,3 +1,13 @@ +<!--- + name: File History Sample + platform: WDM + language: cpp + category: General + description: A console application that starts the file history service, if it is stopped, and schedules regular backups. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617712 +---> + + File History Sample ================== diff --git a/general/filehistory/exe/fhsetup.vcxproj b/general/filehistory/exe/fhsetup.vcxproj index fdb347e1..e6e78377 100644 --- a/general/filehistory/exe/fhsetup.vcxproj +++ b/general/filehistory/exe/fhsetup.vcxproj @@ -97,15 +97,15 @@ <WarningLevel>Level4</WarningLevel> <ExceptionHandling>Sync</ExceptionHandling> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </ClCompile> <Midl> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </Midl> <ResourceCompile> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </ResourceCompile> <Link> <AdditionalDependencies>%(AdditionalDependencies);shell32.lib;shlwapi.lib;Ole32.lib;Oleaut32.lib;User32.lib;fhsvcctl.lib</AdditionalDependencies> @@ -117,15 +117,15 @@ <WarningLevel>Level4</WarningLevel> <ExceptionHandling>Sync</ExceptionHandling> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </ClCompile> <Midl> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </Midl> <ResourceCompile> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </ResourceCompile> <Link> <AdditionalDependencies>%(AdditionalDependencies);shell32.lib;shlwapi.lib;Ole32.lib;Oleaut32.lib;User32.lib;fhsvcctl.lib</AdditionalDependencies> @@ -137,15 +137,15 @@ <WarningLevel>Level4</WarningLevel> <ExceptionHandling>Sync</ExceptionHandling> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </ClCompile> <Midl> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </Midl> <ResourceCompile> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </ResourceCompile> <Link> <AdditionalDependencies>%(AdditionalDependencies);shell32.lib;shlwapi.lib;Ole32.lib;Oleaut32.lib;User32.lib;fhsvcctl.lib</AdditionalDependencies> @@ -157,15 +157,15 @@ <WarningLevel>Level4</WarningLevel> <ExceptionHandling>Sync</ExceptionHandling> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </ClCompile> <Midl> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </Midl> <ResourceCompile> <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE</PreprocessorDefinitions> - <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(SDK_INC_PATH);.</AdditionalIncludeDirectories> </ResourceCompile> <Link> <AdditionalDependencies>%(AdditionalDependencies);shell32.lib;shlwapi.lib;Ole32.lib;Oleaut32.lib;User32.lib;fhsvcctl.lib</AdditionalDependencies> @@ -187,4 +187,4 @@ <ClInclude Exclude="@(ClInclude)" Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd" /> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> -</Project>
\ No newline at end of file +</Project> diff --git a/general/installwdf/README.md b/general/installwdf/README.md index 429957d5..df9e8445 100644 --- a/general/installwdf/README.md +++ b/general/installwdf/README.md @@ -1,3 +1,13 @@ +<!--- + name: WDF Installation Package + platform: Tool + language: cpp + category: General WDF + description: Demonstrates how to install WDF packages on a system. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617713 +---> + + WDF Installation Package ======================== diff --git a/general/ioctl/kmdf/README.md b/general/ioctl/kmdf/README.md index c9a10365..9c3d80d4 100644 --- a/general/ioctl/kmdf/README.md +++ b/general/ioctl/kmdf/README.md @@ -1,3 +1,13 @@ +<!--- + name: Non-PnP Driver Sample + platform: KMDF + language: cpp + category: General WDF + description: Demonstrates how to write a non-PnP driver using the Kernel Mode Driver Framework. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=620307 +---> + + Non-PnP Driver Sample ==================== diff --git a/general/ioctl/kmdf/exe/testapp.c b/general/ioctl/kmdf/exe/testapp.c index a645203e..4e230124 100644 --- a/general/ioctl/kmdf/exe/testapp.c +++ b/general/ioctl/kmdf/exe/testapp.c @@ -198,7 +198,8 @@ GetCoinstallerVersion( VOID ) { - if (FAILED( StringCchPrintf(G_coInstallerVersion, + if (!G_versionSpecified && + FAILED( StringCchPrintf(G_coInstallerVersion, MAX_VERSION_SIZE, "%02d%03d", // for example, "01009" KMDF_VERSION_MAJOR, diff --git a/general/ioctl/wdm/README.md b/general/ioctl/wdm/README.md index fcbf71f2..e9e2e57d 100644 --- a/general/ioctl/wdm/README.md +++ b/general/ioctl/wdm/README.md @@ -1,3 +1,13 @@ +<!--- + name: IOCTL + platform: WDM + language: cpp + category: General + description: Demonstrates usage of four different types of IOCTLs + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617715 +---> + + IOCTL ===== diff --git a/general/obcallback/README.md b/general/obcallback/README.md index ca4069a2..37326565 100644 --- a/general/obcallback/README.md +++ b/general/obcallback/README.md @@ -1,3 +1,13 @@ +<!--- + name: ObCallback Callback Registration Driver + platform: WDM + language: cpp + category: General + description: Demonstrates the use of registered callbacks for process protection. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617716 +---> + + ObCallback Callback Registration Driver ======================================= diff --git a/general/pcidrv/README.md b/general/pcidrv/README.md index 04bf35b5..2fa15558 100644 --- a/general/pcidrv/README.md +++ b/general/pcidrv/README.md @@ -1,3 +1,13 @@ +<!--- + name: PCIDRV - WDF Driver for PCI Device + platform: KMDF + language: cpp + category: General PCI WDF + description: Demonstrates how to write a KMDF driver for a PCI device. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617717 +---> + + PCIDRV - WDF Driver for PCI Device ================================== diff --git a/general/pcidrv/kmdf/HW/PCIDRV.vcxproj b/general/pcidrv/kmdf/HW/PCIDRV.vcxproj index fdf14d4d..763937ed 100644 --- a/general/pcidrv/kmdf/HW/PCIDRV.vcxproj +++ b/general/pcidrv/kmdf/HW/PCIDRV.vcxproj @@ -339,7 +339,7 @@ <ResourceCompile Include="..\pcidrv.rc" /> </ItemGroup> <ItemGroup> - <Inf Exclude="@(Inf)" Include="*.inf" /> + <Inf Exclude="@(Inf)" Include="..\*.inx" /> <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'" /> </ItemGroup> <ItemGroup> diff --git a/general/pcidrv/kmdf/PCIDRV.C b/general/pcidrv/kmdf/PCIDRV.C index e3f65678..17ae76bf 100644 --- a/general/pcidrv/kmdf/PCIDRV.C +++ b/general/pcidrv/kmdf/PCIDRV.C @@ -1,4 +1,3 @@ - /*++ Copyright (c) Microsoft Corporation. All rights reserved. diff --git a/general/pcidrv/kmdf/genpci.inx b/general/pcidrv/kmdf/genpci.inx Binary files differindex b278dcd8..1ccf8ca9 100644 --- a/general/pcidrv/kmdf/genpci.inx +++ b/general/pcidrv/kmdf/genpci.inx diff --git a/general/perfcounters/kcs/README.md b/general/perfcounters/kcs/README.md index 1cbd3ac0..2e7553e5 100644 --- a/general/perfcounters/kcs/README.md +++ b/general/perfcounters/kcs/README.md @@ -1,3 +1,13 @@ +<!--- + name: Kernel Counter Sample (Kcs) + platform: WDM + language: cpp + category: General + description: Demonstrates the use of the kernel-mode performance library. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617718 +---> + + Kernel Counter Sample (Kcs) =========================== diff --git a/general/perfcounters/kcs/kcs.vcxproj b/general/perfcounters/kcs/kcs.vcxproj index 5f30eb23..e97abb07 100644 --- a/general/perfcounters/kcs/kcs.vcxproj +++ b/general/perfcounters/kcs/kcs.vcxproj @@ -151,7 +151,7 @@ <PropertyGroup> <CTRPP_ODIR>$([System.IO.Path]::GetDirectoryName($(ProjectDir)\$(IntDir)))</CTRPP_ODIR> </PropertyGroup> - <Exec Command=""$(WDKContentRoot)\bin\x86\ctrpp.exe" kcs.man -prefix Kcs -o "$(CTRPP_ODIR)\KcsCounters.h" -ch "$(CTRPP_ODIR)\KcsCounters_counters.h" -rc "$(CTRPP_ODIR)\KcsCounters.rc"" WorkingDirectory="$(MSBuildProjectDirectory)" /> + <Exec Command=""ctrpp.exe" kcs.man -prefix Kcs -o "$(CTRPP_ODIR)\KcsCounters.h" -ch "$(CTRPP_ODIR)\KcsCounters_counters.h" -rc "$(CTRPP_ODIR)\KcsCounters.rc"" WorkingDirectory="$(MSBuildProjectDirectory)" /> </Target> <ItemGroup> <ClCompile Include="Kcs.c" /> @@ -170,4 +170,4 @@ <ClInclude Exclude="@(ClInclude)" Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd" /> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> -</Project>
\ No newline at end of file +</Project> diff --git a/general/registry/regfltr/README.md b/general/registry/regfltr/README.md index 9e5a0740..40fe7011 100644 --- a/general/registry/regfltr/README.md +++ b/general/registry/regfltr/README.md @@ -1,3 +1,13 @@ +<!--- + name: RegFltr Sample Driver + platform: WDM + language: cpp + category: General + description: Demonstrates how to write a registry filter driver. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617720 +---> + + RegFltr Sample Driver ===================== diff --git a/general/toaster/toastDrv/README.md b/general/toaster/toastDrv/README.md index 326d40a9..9e9a469a 100644 --- a/general/toaster/toastDrv/README.md +++ b/general/toaster/toastDrv/README.md @@ -1,3 +1,13 @@ +<!--- + name: Toaster Sample Driver + platform: KMDF UMDF1 + language: cpp + category: General WDF + description: An iterative series of samples that demonstrate KDMF and UDMF1 driver development. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=620309 +---> + + Toaster Sample Driver ===================== The Toaster collection is an iterative series of samples that demonstrate fundamental aspects of Windows driver development for both Kernel-Mode Driver Framework (KMDF) and User-Mode Driver Framework (UMDF) version 1. diff --git a/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.inx b/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.inx Binary files differindex 9f7634b1..c51e1e9b 100644 --- a/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.inx +++ b/general/toaster/toastDrv/kmdf/bus/dynamic/dynambus.inx diff --git a/general/toaster/toastDrv/kmdf/bus/static/statbus.inx b/general/toaster/toastDrv/kmdf/bus/static/statbus.inx Binary files differindex 0725d2bb..a28b3144 100644 --- a/general/toaster/toastDrv/kmdf/bus/static/statbus.inx +++ b/general/toaster/toastDrv/kmdf/bus/static/statbus.inx diff --git a/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.inx b/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.inx Binary files differindex 32916e7e..73a1a1ea 100644 --- a/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.inx +++ b/general/toaster/toastDrv/kmdf/func/featured/wdffeatured.inx diff --git a/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.inx b/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.inx Binary files differindex ad55da36..69fbea75 100644 --- a/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.inx +++ b/general/toaster/toastDrv/kmdf/func/simple/wdfsimple.inx diff --git a/general/toaster/toastpkg/README.md b/general/toaster/toastpkg/README.md index 326d40a9..a4763177 100644 --- a/general/toaster/toastpkg/README.md +++ b/general/toaster/toastpkg/README.md @@ -1,5 +1,15 @@ -Toaster Sample Driver -===================== +<!--- + name: Toaster Package Sample Driver + platform: WDM + language: cpp + category: General + description: Simulates hardware-first and software-first installation of the toaster sample driver. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617723 +---> + + +Toaster Package Sample Driver +============================= The Toaster collection is an iterative series of samples that demonstrate fundamental aspects of Windows driver development for both Kernel-Mode Driver Framework (KMDF) and User-Mode Driver Framework (UMDF) version 1. All the samples work with a hypothetical toaster bus, over which toaster devices can be connected to a PC. diff --git a/general/toaster/toastpkg/inf/toastpkg.inf b/general/toaster/toastpkg/inf/toastpkg.inf index f1edae86..04ac6103 100644 --- a/general/toaster/toastpkg/inf/toastpkg.inf +++ b/general/toaster/toastpkg/inf/toastpkg.inf @@ -32,7 +32,6 @@ CatalogFile.NTAMD64 = tstamd64.cat [DestinationDirs] DefaultDestDir = 12 CoInstaller_CopyFiles = 11 -ToasterClassInstallerCopyFiles = 11 ; ================= Class section ===================== @@ -43,12 +42,8 @@ CopyFiles=ToasterClassInstallerCopyFiles [ToasterClassReg] HKR,,,0,%ClassName% HKR,,Icon,,100 -HKR,,Installer32,,"tostrcls.dll,ToasterClassInstaller" HKR,,DeviceCharacteristics,0x10001,0x100 ; Use same security checks on relative opens -[ToasterClassInstallerCopyFiles] -tostrcls.dll - ;***************************************** ; Toaster Device Install Section ;***************************************** @@ -120,7 +115,6 @@ OriginalInfSourcePath = %1% [SourceDisksFiles] toaster.sys = 1,, tostrco2.dll = 1,, -tostrcls.dll = 1,, [Strings] SPSVCINST_ASSOCSERVICE= 0x00000002 diff --git a/general/toaster/toastpkg/toastcd/amd64/tostrcls.dll b/general/toaster/toastpkg/toastcd/amd64/tostrcls.dll Binary files differdeleted file mode 100644 index 80fe0dc0..00000000 --- a/general/toaster/toastpkg/toastcd/amd64/tostrcls.dll +++ /dev/null diff --git a/general/toaster/toastpkg/toastcd/i386/tostrcls.dll b/general/toaster/toastpkg/toastcd/i386/tostrcls.dll Binary files differdeleted file mode 100644 index 7ac337f8..00000000 --- a/general/toaster/toastpkg/toastcd/i386/tostrcls.dll +++ /dev/null diff --git a/general/toaster/toastpkg/toastcd/toastpkg.inf b/general/toaster/toastpkg/toastcd/toastpkg.inf index f1edae86..04ac6103 100644 --- a/general/toaster/toastpkg/toastcd/toastpkg.inf +++ b/general/toaster/toastpkg/toastcd/toastpkg.inf @@ -32,7 +32,6 @@ CatalogFile.NTAMD64 = tstamd64.cat [DestinationDirs] DefaultDestDir = 12 CoInstaller_CopyFiles = 11 -ToasterClassInstallerCopyFiles = 11 ; ================= Class section ===================== @@ -43,12 +42,8 @@ CopyFiles=ToasterClassInstallerCopyFiles [ToasterClassReg] HKR,,,0,%ClassName% HKR,,Icon,,100 -HKR,,Installer32,,"tostrcls.dll,ToasterClassInstaller" HKR,,DeviceCharacteristics,0x10001,0x100 ; Use same security checks on relative opens -[ToasterClassInstallerCopyFiles] -tostrcls.dll - ;***************************************** ; Toaster Device Install Section ;***************************************** @@ -120,7 +115,6 @@ OriginalInfSourcePath = %1% [SourceDisksFiles] toaster.sys = 1,, tostrco2.dll = 1,, -tostrcls.dll = 1,, [Strings] SPSVCINST_ASSOCSERVICE= 0x00000002 diff --git a/general/toaster/umdf2/README.md b/general/toaster/umdf2/README.md index 9dcdd158..75cf882b 100644 --- a/general/toaster/umdf2/README.md +++ b/general/toaster/umdf2/README.md @@ -1,3 +1,13 @@ +<!--- + name: Toaster Sample (UMDF version 2) + platform: UMDF2 + language: cpp + category: General WDF + description: An iterative series of samples that demonstrate driver development using UMDF version 2. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=620310 +---> + + Toaster Sample (UMDF Version 2) =============================== The Toaster (UMDF version 2) sample is an iterative series of samples that demonstrate fundamental aspects of Windows driver development. diff --git a/general/toaster/umdf2/filter/generic/filterum.inx b/general/toaster/umdf2/filter/generic/filterum.inx Binary files differindex 6686b2fb..0efeb0d3 100644 --- a/general/toaster/umdf2/filter/generic/filterum.inx +++ b/general/toaster/umdf2/filter/generic/filterum.inx diff --git a/general/toaster/umdf2/func/featured/wdffeaturedum.inx b/general/toaster/umdf2/func/featured/wdffeaturedum.inx Binary files differindex 067ca605..bb8af311 100644 --- a/general/toaster/umdf2/func/featured/wdffeaturedum.inx +++ b/general/toaster/umdf2/func/featured/wdffeaturedum.inx diff --git a/general/toaster/umdf2/func/simple/wdfsimpleum.inx b/general/toaster/umdf2/func/simple/wdfsimpleum.inx Binary files differindex 18576c76..3187b27f 100644 --- a/general/toaster/umdf2/func/simple/wdfsimpleum.inx +++ b/general/toaster/umdf2/func/simple/wdfsimpleum.inx diff --git a/general/tracing/SystemTraceControl/README.md b/general/tracing/SystemTraceControl/README.md index eb044ddb..b45ae788 100644 --- a/general/tracing/SystemTraceControl/README.md +++ b/general/tracing/SystemTraceControl/README.md @@ -1,3 +1,13 @@ +<!--- + name: System Trace Control + platform: Application + language: cpp + category: General Tracing + description: Demonstrates how to use event tracing control APIs to collect events from the system trace provider. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617725 +---> + + SystemTraceProvider =================== diff --git a/general/tracing/SystemTraceControl/SystemTraceControl.vcxproj b/general/tracing/SystemTraceControl/SystemTraceControl.vcxproj index 7669ebaa..1d635e7e 100644 --- a/general/tracing/SystemTraceControl/SystemTraceControl.vcxproj +++ b/general/tracing/SystemTraceControl/SystemTraceControl.vcxproj @@ -26,22 +26,22 @@ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> - <PlatformToolset>v140</PlatformToolset> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> - <PlatformToolset>v140</PlatformToolset> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> - <PlatformToolset>v140</PlatformToolset> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> - <PlatformToolset>v140</PlatformToolset> + <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> diff --git a/general/tracing/evntdrv/README.md b/general/tracing/evntdrv/README.md index 4e64ecae..41359ad1 100644 --- a/general/tracing/evntdrv/README.md +++ b/general/tracing/evntdrv/README.md @@ -1,3 +1,13 @@ +<!--- + name: Eventdrv + platform: Application + language: cpp + category: General Tracing + description: Demonstrates the use of the Event Tracing for Windows (ETW) API in a driver. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617724 +---> + + Eventdrv ======== diff --git a/general/tracing/tracedriver/README.md b/general/tracing/tracedriver/README.md index 064fb133..358053a1 100644 --- a/general/tracing/tracedriver/README.md +++ b/general/tracing/tracedriver/README.md @@ -1,3 +1,13 @@ +<!--- + name: Tracedrv + platform: Application + language: cpp + category: General Tracing + description: A sample driver instrumented for software tracing. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617726 +---> + + Tracedrv ======== diff --git a/general/umdfSkeleton/README.md b/general/umdfSkeleton/README.md index 923f44df..022722c1 100644 --- a/general/umdfSkeleton/README.md +++ b/general/umdfSkeleton/README.md @@ -1,3 +1,13 @@ +<!--- + name: UMDF Driver Skeleton Sample (UMDF version 1) + platform: UMDF1 + language: cpp + category: General WDF + description: Demonstrates how to use UDMF to write a minimal driver. + samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=617727 +---> + + UMDF Driver Skeleton Sample (UMDF Version 1) ============================================ diff --git a/general/umdfSkeleton/UMDFSkeleton.vcxproj b/general/umdfSkeleton/UMDFSkeleton.vcxproj index 54fa7d0f..53f8195c 100644 --- a/general/umdfSkeleton/UMDFSkeleton.vcxproj +++ b/general/umdfSkeleton/UMDFSkeleton.vcxproj @@ -238,7 +238,7 @@ <ResourceCompile Include="Skeleton.rc" /> </ItemGroup> <ItemGroup> - <Inf Exclude="@(Inf)" Include="*.inf" /> + <Inf Exclude="@(Inf)" Include="*.inx" /> <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'" /> </ItemGroup> <ItemGroup> |
