CustomAction succeeds on development computer, fails on deployment computer - c

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.

Related

SFML D bindings: libsfml-system.so.2.5: cannot open shared object file:

I recently did a fresh install of CSFML and I am getting this errors when running my program:
object.Exception#source/app.d(38): Fatal error(s) encountered whilst calling `loadSFML()` function:
["Error: libcsfml-system.so, Message: libsfml-system.so.2.5: cannot open shared object file: No such file or directory",
"Error: libcsfml-system.so.2, Message: libcsfml-system.so.2: cannot open shared object file: No such file or directory",
"Error: libcsfml-system.so.2.0, Message: libcsfml-system.so.2.0: cannot open shared object file: No such file or directory"]
I am using SFML D bindings (https://github.com/BindBC/bindbc-sfml):
void loadDyn() {
if (!loadSFML()) {
string[] messages;
foreach (const(ErrorInfo) err; errors) {
string errorStr = to!string(err.error);
string messageStr = to!string(err.message);
messages ~= format("Error: %s, Message: %s", errorStr, messageStr);
}
throw new Exception(format("Fatal error(s) encountered whilst calling `loadSFML()` function: %s", messages));
}
}
void main() {
loadDyn();
sfRenderWindow* renderWindow = sfRenderWindow_create(sfVideoMode(500, 500), "Snake Smooth Dynamics", sfWindowStyle.sfDefaultStyle, null);
sfEvent event;
while (renderWindow.sfRenderWindow_isOpen()) {
while (renderWindow.sfRenderWindow_pollEvent(&event)) {
if (event.type == sfEventType.sfEvtClosed) {
renderWindow.sfRenderWindow_close();
}
}
renderWindow.sfRenderWindow_clear(sfYellow);
renderWindow.sfRenderWindow_drawSprite(snakeHeadSprite, null);
renderWindow.sfRenderWindow_display();
}
}
Things I've tried:
I found someone with a similar question: Linux SFML - Cannot Open Shared Object File, tried out some answers but to no avail
I tried to sudo apt purge every CSFML dependency (graphics, audo, etc) and reinstall each component (csfml-audio, csfml-graphics) manually etc, to no avail.
I tried to run sudo ldconfig... didn't work
As a last ditch effort I tried to manually move the shared object files to the /usr/local/lib directory (to try and perhaps trick the compiler to run the program?) but to no avail.
I tried to run on a new VM and still didn't work
I tried to set LD_LIBRARY_PATH environment variable
The amount of layers I depend on make it impossible to find where the bug is from, there are a lot of separate things going on and it's very multilayered, I don't know where the issue is specifically coming from as it used to work just fine I ran the exact same commands to install CSFML previously, now when I do it it just refuses to run.
The weird thing is when I ran a brand new virtual machine, installed those packages, still same issue.
I am running Linux Mint 21.1, Ubuntu based. Relatively new PC.

How do I check if my executable is running for a service or for a normal program?

I'm developing a win service in using mingw I've been trying for hours
I looked for examples on the internet I used ChatGPT
and nothing it returned works and the few examples I found
had nothing to do with what I wanted
I hope there is some way to do this the
idea and before i create the SERVICE_TABLE_ENTRY i can check if my executable was started
for a windows service,
if yes i create the
SERVICE_TABLE_ENTRY if I don't do anything else.
If your program supports multiple modes then I would suggest using a command line parameter like /service for the service registration.
Alternatively you could check if your process token contains S-1-5-6 (SECURITY_SERVICE_RID) but I'm not sure which Windows version that was introduced.
If you want to check if it's running you should check if the service is running. Check under services by running services.msc and looking for the service you registered.
Some time ago I wrote a simple library to make your program a service (on Windows) or daemon (on *nix):
https://sourceforge.net/projects/daemonservice/
Maybe you can check the source on how it was done there...
I saw a simple way to check this just create SERVICE_TABLE_ENTRY and use StartServiceCtrlDispatcher if it returns an error probably the executable was started like a normal program.
SERVICE_TABLE_ENTRY _dispatcher_entry_table[] =
{
{"", (LPSERVICE_MAIN_FUNCTION)serviceMain},
{NULL, NULL}
};
if (!StartServiceCtrlDispatcher(_dispatcher_entry_table))
{
DWORD __error_code = GetLastError();
if (__error_code == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
{
//It's probably a normal program
}
else
{
//handle the errors
}
}

SHCreateItemFromParsingName return FILE_NOT_FOUND when filename specified

I try get IShellItem for a file to copy it with IFileOperation COM interface from system directory to another directory. I must use exactly IFileOperation COM interface for this purpose.
When I specify full filename - return value from SHCreateItemFromParsingName() was ERROR_FILE_NOT_FOUND, but file present in the directory. When I delete filename from path below and use only folder path - all seems good, return value is S_OK.
//...
CoInitialize(NULL);
//...
WCHAR szSourceDll[MAX_PATH * 2];
wcscpy_s(szSourceDll, MAX_PATH, L"C:\\Windows\\System32\\sysprep\\cryptbase.dll");
r = CoCreateInstance(&CLSID_FileOperation, NULL, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_HANDLER, &IID_IFileOperation, &FileOperation1);
if (r != S_OK) return;
FileOperation1->lpVtbl->SetOperationFlags(FileOperation1, FOF_NOCONFIRMATION | FOFX_NOCOPYHOOKS | FOFX_REQUIREELEVATION);
r = SHCreateItemFromParsingName(szSourceDll, NULL, &IID_IShellItem, &isrc);
//...
CoUninitialize();
//...
Why this code, written in C, not working with filenames. How can I create IShellItem instance for file in system folder to copy it?
P.S.
Windows 7 x64, C, Visual Studio 2015, v140 platform toolset, additional dependencies: Msi.lib;Wuguid.lib;ole32.lib;ntdll.lib
P.P.S
It's properly work with files in user`s directories...
Assuming your application is compiled as a 32-bit application and running on a 64-bit OS, a file not found error is probably correct because your application is redirected to the 32-bit system directory (%WinDir%\SysWoW64).
In most cases, whenever a 32-bit application attempts to access %windir%\System32, %windir%\lastgood\system32, or %windir%\regedit.exe, the access is redirected to an architecture-specific path.
For more information, see File System Redirector on MSDN.
You could temporarily turn off redirection in your thread but it is not really safe to do this when calling shell functions, only functions in kernel32. If the API you are calling internally uses LoadLibrary and/or COM then the API might fail because it will be unable to load from system32 while redirection is disabled.
You can also access the native system32 directory with the %WinDir%\SysNative backdoor. This only works in 32-bit applications on 64-bit Vista+ so you must do some version detection.

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!

Why am I getting Error Code 6 on StartService?

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.

Resources