Why am I getting Error Code 6 on StartService? - c

For my purposes, I need to write a kernel mode driver for Windows. Currently I am attempting to make it work under Windows 7 x64.
I created a simple project in Visual Studio 2012 with default code for a KMDF driver. I compiled the code with test-signing on. The driver was compiled and signed.
I also have Test-Signing ON enabled as clearly displayed on the bottom left corner of my Desktop.
Upon trying to start the driver as a service, I always get an Error Code 6: Invalid Handle error.(I have since simplified the code to just try and start it but still did not work;default code did not work either)
Basically, I am having the same problem as the question asked here
https://stackoverflow.com/questions/12080157/startservice-error-6
unfortunately he was never answered. I tried the provided solution, but it didn't help either.
My code that tries to start the driver is
int _cdecl main(void)
{
HANDLE hSCManager;
HANDLE hService;
SERVICE_STATUS ss;
hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
printf("Load Driver\n");
if(hSCManager)
{
printf("Create Service\n");
hService = CreateService(hSCManager, "Example",
"Example Driver",
SERVICE_ALL_ACCESS | SERVICE_START | DELETE | SERVICE_STOP ,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_IGNORE,
"\\path\\to\\driver\\KMDFDriver1.sys",
NULL, NULL, NULL, NULL, NULL);
if(!hService)
{
hService = OpenService(hSCManager, "Example",
SERVICE_ALL_ACCESS | SERVICE_START | DELETE | SERVICE_STOP);
if(!hService)
{
// If initial startup of the driver failed, it will fail here.
process_error();
return 0;
}
}
if(hService)
{
printf("Start Service\n");
if(StartService(hService, 0, NULL) == 0)
{
// Start service ALWAYS returns 0. Only when executed for the first time. Next time it fails on OpenService.
process_error();
printf("Did not start!\n");
}
printf("Press Enter to close service\r\n");
getchar();
ControlService(hService, SERVICE_CONTROL_STOP, &ss);
DeleteService(hService);
CloseServiceHandle(hService);
}
CloseServiceHandle(hSCManager);
}
return 0;
}
And this is the driver code
DRIVER_INITIALIZE DriverEntry;
#ifdef ALLOC_PRAGMA
#pragma alloc_text (INIT, DriverEntry)
#endif
NTSTATUS
DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
{
WDF_DRIVER_CONFIG config;
NTSTATUS status;
DbgPrint("Hello World!\n");
WDF_DRIVER_CONFIG_INIT(&config,
NULL
);
config.DriverInitFlags = WdfDriverInitNonPnpDriver;
status = WdfDriverCreate(DriverObject,
RegistryPath,
WDF_NO_OBJECT_ATTRIBUTES,
&config,
WDF_NO_HANDLE
);
if (!NT_SUCCESS(status)) {
KdPrint( ("WdfDriverCreate failed with "
"status 0x%x\n", status));
}
return status;
}
The function process_error() is a wrapper around GetLastError() which in addition to providing the numeric value, displays a text version of the error code.
I have exhausted all options provided to me to solve this issue. A google search revealed only one occurrence of this problem, and the question was asked here.
What could the problem be?
Extra notes: The driver was compiled with Visual Studio 2012 Ultimate, while my startup code was compiled with MinGW-W64(using GCC). But the startup code shouldn't matter as much as the driver.
Extra notes 2: After wondering for a long time what could be wrong I started thinking if it's the test-sign certificate, because I tried driver source code provided from MSDN, and upon successful compilation, I still got ERROR_INVALID_HANDLE(Error Code 6) when trying to start it.
I have still not found a solution.

I tracked this down to the project settings of the driver. The KMDF versions were missing from the project.
Adjust the following (under Driver Model Settings):
- KMDF Version Major = 1
- KMDF Version Minor = 9
Hit OK, recompile, and reinstall. Worked for me!

A few thoughts:
You're using HANDLE hSCManager && HANDLE hService, they should be declared as SC_HANDLE
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682450(v=vs.85).aspx
"lpBinaryPathName [in, optional]
The fully qualified path to the service binary file. If the path contains a space, it must be quoted so that it is correctly interpreted. For example, "d:\my share\myservice.exe" should be specified as "\"d:\my share\myservice.exe\"".
Try using the full path to the driver

I had the same problem with starting my kernel driver:
startservice failed 6:
the handle is invalid
Turned out that the "classID GUID" of the driver was the same as that of an other one (found out through device manager, looking in events showed different driver names).
Used an online generator to make a new GUID and replaced the one that's in the .inf file of the project (in VS, not any texteditor or some).
After a rebuild and deployment on target machine everything worked fine.
Hope this helps...

Run visual studio with admin privilege

Your call to OpenSCManager() is only asking for SC_MANAGER_CREATE_SERVICE permission by itself, which is not enough for OpenService() or StartService() to succeed.

Related

CLion won't show output in Debug

When I start up the program, this is the output:
-------------------- HASHMAP MANAGEMENT BOOT MENU -------------------------
Would you like to:
(a) create a new hashmap
(b) load an existing one
(q) exit
>
However, when debugging, none of this shows up. Checking the debug, it does go over the printf() commands, but it just refuses to let them show up in the console. Input registers, but output never comes.
int main(void){
bool on = true;
char choice = ' ';
int status = 0;
while(on){
if(status == -1){
printf("\n[ERROR] : HASHMAP NOT INITIALISED\n");
}
printf("\n-------------------- HASHMAP MANAGEMENT BOOT MENU -------------------------\n");
printf("Would you like to:\n(a) create a new hashmap\n(b) load an existing one\n(q) exit\n> ");
scanf("%c",&choice);
...
...
}
}
This is how the start of the code is, excluding all the #includes. Also, for some reason, CLion says the code I'm building is task2-a.c | Debug if that's any help. task2-a.c being the name of the C file that's being built. I dunno what's going on...
Update: Debugging works great on Ubuntu 17.04 Clion 2017.2. It just doesn't work on Windows 10 CLion 2017.3.
Putting setbuf(stdout, 0); before any printf statement or any output happens fixed this problem.
If you don't care to use the built-in clion console, you can solve the issue by changing the default debugger used by clion.
Under Settings => Toolchain => <your compiler> => Debugger change Bundled GDB to your compiler's debugger, e.g. MinGW:

UpdateDriverForPlugAndPlayDevicesW returns fails with error code ERROR_FILE_NOT_FOUND even file already exists

I am compiling and running the project libwdi. It is a USB driver installer for windows.
In the part where an INF should be installed using UpdateDriverForPlugAndPlayDevicesW() function, it returns FALSE 0 and the GetLastError() value is 2 which corresponds to ERROR_FILE_NOT_FOUND.
ret = UpdateDriverForPlugAndPlayDevicesW(hwndParent, wHardwareId, wFullInfPath, InstallFlags, bRebootRequired);
err = GetLastError();
I debugged the code, made sure that wFullInfPath exists in the system and the wHardwareId is correct as specified in device manager, also
bRebootRequired is NULL,
InstallFlags is INSTALLFLAG_FORCE.
Why is the driver not installed ? Why UpdateDriverForPlugAndPlayDevicesW() does not return TRUE?
It turned out that the library, which generates the INF file, produces a defected INF file. It has some placeholders for unneeded files which makes Windows search for these non-existing files.

How to start a self-written driver

I wrote a driver in Visual Studio 2013. The building-Process was successful.
Then I prepared a traget-computer and copied the driver-files to it.
Then I installed the driver:
C:\Windows\system32>pnputil -a "E:\driverZeug\KmdfHelloWorldPackage\KmdfHelloWorld.inf"
Microsoft-PnP-Dienstprogramm
Verarbeitungsinf.: KmdfHelloWorld.inf
Das Treiberpaket wurde erfolgreich hinzugefügt.
Veröffentlichter Name: oem42.inf
Versuche gesamt: 1
Anzahl erfolgreicher Importe: 1
It seems like it was successful.
I ran DebugView on the PC but now I don't know how to start the driver, so that I can see a debug-output. I have a DbgPrintEx()-Statement in my sourcecode.
Can someone tell me how to start this driver so that I can see the output.
This is the sourcecode of the driver:
#include <ntddk.h>
#include <wdf.h>
DRIVER_INITIALIZE DriverEntry;
EVT_WDF_DRIVER_DEVICE_ADD KmdfHelloWorldEvtDeviceAdd;
NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath)
{
NTSTATUS status;
WDF_DRIVER_CONFIG config;
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: DriverEntry\n");
KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: DriverEntry\n"));
WDF_DRIVER_CONFIG_INIT(&config, KmdfHelloWorldEvtDeviceAdd);
status = WdfDriverCreate(DriverObject, RegistryPath, WDF_NO_OBJECT_ATTRIBUTES, &config, WDF_NO_HANDLE);
return status;
}
NTSTATUS KmdfHelloWorldEvtDeviceAdd(_In_ WDFDRIVER Driver, _Inout_ PWDFDEVICE_INIT DeviceInit)
{
NTSTATUS status;
WDFDEVICE hDevice;
UNREFERENCED_PARAMETER(Driver);
KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: KmdfHelloWorldEvtDeviceAdd\n"));
status = WdfDeviceCreate(&DeviceInit, WDF_NO_OBJECT_ATTRIBUTES, &hDevice);
return status;
}
You need to make an EXE(testapp) that starts your driver if installation is already done. You can use below code in the application:
SC_HANDLE schService;
SC_HANDLE schSCManager;
schSCManager = OpenSCManager(NULL, // local machine
NULL, // local database
SC_MANAGER_ALL_ACCESS // access required
);
// Open the handle to the existing service.
schService = OpenService(SchSCManager,
DriverName, //name of the driver
SERVICE_ALL_ACCESS
);
StartService(schService, // service identifier
0, // number of arguments
NULL // pointer to arguments
));
You need add code according to your need. Try this.
For more info download the samples drivers and test apps provided by microsoft.
You can use the built-in command line "sc" (service control) tool to start the driver.
The syntax is:
sc start <name>
So if your driver is installed with the name "KmdfHelloWorld" the command should be:
sc start KmdfHelloWorld
Currently, I am writing a GPIO Controller/Driver for Windows 8.1 & Windows 10 and have had similar issues. The easiest way to start your driver is to set up and provision a computer for driver testing and using Visual Studio to deploy, install, and start your driver on a remote machine.
It's good practice to write your driver then deploy and test remotely (either on another computer, or a VM such as VirtualBox), as this decrease your chances of messing up the computer you are writing code on.
To provision a computer, I used the following MSDN page:
https://msdn.microsoft.com/en-us/library/windows/hardware/dn745909?f=255&MSPPError=-2147217396
By running the prepackaged tests, you can actually have VS and Windows report on the status of the driver, get debugging info, and even set breakpoints. Trust me, for starters this is the easiest way to do this.
Also, it wouldn't hurt to register and create the callback function for the default working state, that way your driver actually does something while running. For this, use the EVT_WDF_DEVICE_D0_ENTRY define like you did for the EVT_WDF_DRIVER_DEVICE_ADD.
Happy Coding!

CustomAction succeeds on development computer, fails on deployment computer

I'm creating a WiX installer to install a program which connects to a database. To help with this, I've created a C dll which checks to see if a certain instance of SQL exists on a server:
extern "C" UINT __stdcall DBConTest(MSIHANDLE hInstaller)
{
FILE *fp;
fp = fopen("dbcontestdll.txt", "w");
_ConnectionPtr pCon;
int iErrCode;
HRESULT hr;
UINT rc;
//init COM
fwprintf(fp, L"entering dbcontest\n");
if(FAILED(hr = CoInitializeEx(NULL,tagCOINIT::COINIT_APARTMENTTHREADED)))
return ERROR_INVALID_DATA;
fwprintf(fp,L"did coinit\n");
if(FAILED(hr = pCon.CreateInstance(__uuidof(Connection))))
return ERROR_INVALID_DATA;
fwprintf(fp,L"created instance of connection\n");
TCHAR constr[1024];
DWORD constrlen = sizeof(constr);
rc=MsiGetProperty(hInstaller,TEXT("DBCONNECTIONSTRING"), constr, &constrlen);
fwprintf(fp, L"dbconstring is: %s\n", constr);
TCHAR serverstr[1024];
DWORD serverstrlen = sizeof(serverstr);
rc = MsiGetProperty(hInstaller,TEXT("SQLINSTANCE"),serverstr,&serverstrlen);
fwprintf(fp, L"SQLINSTANCE is: %sl\n",serverstr);
TCHAR finalconstr[2048];
swprintf(finalconstr,L"%s; Data Source=%s;",constr,serverstr);
try{
hr = pCon->Open(finalconstr,TEXT(""),TEXT(""),adConnectUnspecified);
}
catch(_com_error ce){
fwprintf(fp, L"%s\n", msg);
::MessageBox(NULL,msg,NULL,NULL);
CoUninitialize();
MsiSetProperty(hInstaller,TEXT("DBCONNECTIONVALID"),TEXT("0"));
return ERROR_SUCCESS;
}
if(FAILED(hr)){
MsiSetProperty(hInstaller,TEXT("DBCONNECTIONVALID"),TEXT("0"));
return ERROR_SUCCESS;
}
pCon->Close();
CoUninitialize();
MsiSetProperty(hInstaller,TEXT("DBCONNECTIONVALID"),TEXT("1"));
::MessageBox(NULL,TEXT("Successfully connected to the database!"),NULL,NULL);
fwprintf(fp, L"leaving...\n");
fclose(fp);
return ERROR_SUCCESS;
}
Now, when I build this function into a dll and add it to my WiX project, this code works on my development machine (specifically, the installation successfully finishes and the file "dbcontestdll.txt" exists and has the correct data in it)--but, when I run it on a "fresh install" machine, the installation fails with exit code 2896 and the "dbcontestdll.txt" is not created.
Are there prerequisites to using C-based dlls in a Windows Installer, such as the C++ redistributable?
You probably don't want to get yourself into the situation where you have to bootstrap C++ redists just to run a Custom Action. Have you tried using the File | New | C++ Custom Action probject that comes with WiX? You can use that to stub out your CA and then copy and paste your code into it. That should give you all the compiler and linker settings that you need to avoid this problem.
For custom actions, I highly recommend statically linking to the C run time. The custom aciton DLL ends up a little bigger but you'll have one less dependency on files outside the custom action.
Yes you probably need the visual c runtime. Dependency Walker might assist finding the required dlls.
Look at this example how to use a Bootstrapper. This way you can install the runtime before the msi will be run. I use the following bootstrapper line:
<BootstrapperFile Include="Microsoft.Visual.C++.9.0.x86">
<ProductName>Visual C++ 2008 Runtime Libraries (x86)</ProductName>
</BootstrapperFile>
This package is normally stored in the C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\vcredist_x86 directory.
I had this problem also. I had an MFC DLL that was dynamically linking by default, and I forgot to include MSVCR100.DLL in the package. Of course it worked fine on the development machine, it even worked on most customers' machines, but it failed on an old Vista PC. I switched to statically linked.

How can I make the printer work in C in MS VC++ Express edition?

I am using VC++ 2008 express edition for C. When I try to run this:
/* Demonstrates printer output. */
#include <stdio.h>
main()
{
float f = 2.0134;
fprintf(stdprn, "This message is printed.\n\n");
fprintf(stdprn, "And now some numbers:\n\n");
fprintf(stdprn, "The square of %f is %f.", f, f*f);
/* Send a form feed */
fprintf(stdprn, "\f");
}
I get four of these errors: error C2065: 'stdprn' : undeclared identifier.
On this forum, they wrote that it works to define the printer as follows:
FILE *printer;
printer = fopen("PRN", "w");
EDIT
It builds with a warning that fopen is unsafe. When it runs the error appears:
Debug Assertion fails.
File: f:\dd\vctools\crt_bld\self_x86\crt\src\fprintf.c
Line: 55
Expression: (str != NULL)
The stdprn stream was an extension provided by Borland compilers - as far as I know, MS have never supported it. Regarding the use of fopen to open the printer device, I don't think this will work with any recent versions of Windows, but a couple of things to try:
use PRN: as the name instead of PRN (note the colon)
try opening the specific device using (for example) LPT1: (once again, note the colon). This will of course not work if you don't have a printer attached.
don't depend on a printer dialog coming up - you are not really using the WIndows printing system when you take this approach (and so it probably won't solve your problem, but is worth a try).
I do not have a printer attached, but I do have the Microsoft XPS document writer installed, s it shoulod at least bring up the standard Windows Print dialog from which one can choose the printer.
No. It wouldn't bring up a dialogue. This is because you are flushing data out to a file. And not going through the circuitous Win32 API.
The print doesn't work because the data is not proper PDL -- something that the printer could understand. For the print to work fine, you need to push in a PDL file, with language specific constructs. This varies from printer to printer, a PS printer will need you to push in a PostScript snippet, a PCL -- a PCL command-set and in case of MXDW you will have to write up XML based page description markup and create a zip file (with all resources embedded in it) i.e. an XPS file to get proper printout.
The PDL constructs are important because otherwise the printer doesn't know where to put the data, which color to print it on, what orientation to use, how many copies to print and so on and so forth.
Edit: I am curious why you are doing this. I understand portability is probably something you are trying to address. But apart from that, I'd like to know, there may be better alternatives available. Win32 Print Subsytem APIs are something that you ought to lookup if you are trying to print programmatically on Windows with any degree of fidelity.
Edit#2:
EDIT It builds with a warning that fopen is unsafe.
This is because MS suggests you use the safer versions nowadays fopen_s . See Security Enhancements in the CRT.
When it runs the error appears:
Debug Assertion fails. File: f:\dd\vctools\crt_bld\self_x86\crt\src\fprintf.c Line: 55
Expression: (str != NULL)
This is because fopen (whose return value you do not check) returns a NULL pointer. The file open failed. Also, if it did succeed a matching fclose call is called for.
There's no such thing as stdprn in ANSI C, it was a nonstandard extension provided by some compilers many years ago.
Today to print you have to use the specific APIs provided on your platform; to print on Windows you have to use the printing APIs to manage the printing of the document and obtain a DC to the printer and the GDI APIs to perform the actual drawing on the DC.
On UNIX-like OSes, instead, usually CUPS is used.
You can substitute the printer using this command with net use, see here on the MSDN kb
NET USE LPT1 \\server_name\printer_name
There is an excellent chapter on printing in DOS using the BIOS, ok, its a bit antiquated but interesting to read purely for nostalgic sake.
Onto your problem, you may need to use CreateFile to open the LPT1 port, see here for an example, I have it duplicated it here, for your benefit.
HANDLE hFile;
hFile = CreateFile("LPT1", GENERIC_WRITE, 0,NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
// handle error
}
OVERLAPPED ov = {};
ov.hEvent = CreateEvent(0, false, false, 0);
char szData[] = "1234567890";
DWORD p;
if (!WriteFile(hFile,szData, 10, &p, &ov))
{
if (GetLastError() != ERROR_IO_PENDING)
{
// handle error
}
}
// Wait for write op to complete (maximum 3 second)
DWORD dwWait = WaitForSingleObject(ov.hEvent, 3000);
if (dwWait == WAIT_TIMEOUT)
{
// it took more than 3 seconds
} else if (dwWait == WAIT_OBJECT_0)
{
// the write op completed,
// call GetOverlappedResult(...)
}
CloseHandle(ov.hEvent);
CloseHandle(hFile);
But if you insist on opening the LPT1 port directly, error checking is omitted...
FILE *prn = fopen("lpt1", "w");
fprintf(prn, "Hello World\n\f");
fclose(prn);
Hope this helps,
Best regards,
Tom.

Resources