0

I have been tasked to create a Windows Service DLL to be hosted by SvcHost.exe using the g++ compiler. So far, I've set up the service, created a DLL with ServiceMain, added "ServiceDLL" into the SYSTEM registry, and added "(group name)" into the SOFTWARE registry.

I used the documentation found at Microsoft - Writing a ServiceMain Function and have followed every rabbit hole in the MSDN catalog. The ONE thing that I have not done is download Visual Studio.

Using other services as a comparison, it seems that my creation of a service is correct and the registry is correct. My code should be correct... so the only thing that I didn't follow the instruction are is the compilation method.

Thus my question: "How do you compile a Service DLL to be hosted using SvcHost.exe with g++?"

Disclaimer: I know that Microsoft has suggested not to use SvcHost.exe but I am not in charge of the project or it's design; I am just a peon.

Currently, I am doing the following to compile...

c:\> g++ -c svchostdemo.cpp
c:\> g++ -shared -o SvcHostDemo.dll svchostdemo.o

And I did the following to create the service...

c:\> sc create SvcHostDemo binpath= "%SystemRoot%\System32\svchost.exe -k demo" type= share

The following keys have been added/modified...

HKLM\SYSTEM\CurrentControlSet\services\SvcHostDemo\Parameters\ServiceDLL = %SystemRoot%\System32\SvcHostDemo.dll

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost\demo = SvcHostDemo

This is what I get when I start the service...

C:\Windows>sc start SvcHostDemo

SERVICE_NAME: SvcHostDemo
        TYPE               : 20  WIN32_SHARE_PROCESS
        STATE              : 2  START_PENDING
                                (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x7d0
        PID                : 6844
        FLAGS              :

This is what I get when I query the service...

C:\Windows>sc query SvcHostDemo

SERVICE_NAME: SvcHostDemo
        TYPE               : 20  WIN32_SHARE_PROCESS
        STATE              : 1  STOPPED
        WIN32_EXIT_CODE    : 193  (0xc1)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

The DLL Code...

#include <windows.h>

#define SVCNAME TEXT("SvcHostDemo")

SERVICE_STATUS          gSvcStatus;
SERVICE_STATUS_HANDLE   gSvcStatusHandle;
HANDLE                  ghSvcStopEvent = NULL;
LPHANDLER_FUNCTION      SvcCtrlHandler;

VOID SvcInit( DWORD dwArgc, LPTSTR *lpszArgv);
VOID ReportSvcStatus( DWORD dwCurrentState,
                      DWORD dwWin32ExitCode,
                      DWORD dwWaitHint);

//
// Purpose:
//   Entry point for the service
//
// Parameters:
//   dwArgc - Number of arguments in the lpszArgv array
//   lpszArgv - Array of strings. The first string is the name of
//     the service and subsequent strings are passed by the process
//     that called the StartService function to start the service.
//
// Return value:
//   None.
//
VOID WINAPI ServiceMain( DWORD dwArgc, LPTSTR *lpszArgv )
{
    // Register the handler function for the service

    gSvcStatusHandle = RegisterServiceCtrlHandler(
        SVCNAME,
        SvcCtrlHandler);

    if( !gSvcStatusHandle )
    {
        MessageBox(NULL, "FAIL", "FAIL", MB_OK | MB_ICONQUESTION);
        //SvcReportEvent(TEXT("RegisterServiceCtrlHandler"));
        return;
    }

    MessageBox(NULL, "PASS", "PASS", MB_OK | MB_ICONQUESTION);

    // These SERVICE_STATUS members remain as set here

    gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    gSvcStatus.dwServiceSpecificExitCode = 0;

    // Report initial status to the SCM

    ReportSvcStatus( SERVICE_START_PENDING, NO_ERROR, 3000 );

    // Perform service-specific initialization and work.

    SvcInit( dwArgc, lpszArgv );
}

//
// Purpose:
//   The service code
//
// Parameters:
//   dwArgc - Number of arguments in the lpszArgv array
//   lpszArgv - Array of strings. The first string is the name of
//     the service and subsequent strings are passed by the process
//     that called the StartService function to start the service.
//
// Return value:
//   None
//
VOID SvcInit( DWORD dwArgc, LPTSTR *lpszArgv)
{
    // TO_DO: Declare and set any required variables.
    //   Be sure to periodically call ReportSvcStatus() with
    //   SERVICE_START_PENDING. If initialization fails, call
    //   ReportSvcStatus with SERVICE_STOPPED.

    // Create an event. The control handler function, SvcCtrlHandler,
    // signals this event when it receives the stop control code.

    ghSvcStopEvent = CreateEvent(
                         NULL,    // default security attributes
                         TRUE,    // manual reset event
                         FALSE,   // not signaled
                         NULL);   // no name

    if ( ghSvcStopEvent == NULL)
    {
        ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
        return;
    }

    // Report running status when initialization is complete.

    ReportSvcStatus( SERVICE_RUNNING, NO_ERROR, 0 );

    // TO_DO: Perform work until service stops.

    while(1)
    {
        // Check whether to stop the service.

        WaitForSingleObject(ghSvcStopEvent, INFINITE);

        ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
        return;
    }
}

//
// Purpose:
//   Sets the current service status and reports it to the SCM.
//
// Parameters:
//   dwCurrentState - The current state (see SERVICE_STATUS)
//   dwWin32ExitCode - The system error code
//   dwWaitHint - Estimated time for pending operation,
//     in milliseconds
//
// Return value:
//   None
//
VOID ReportSvcStatus( DWORD dwCurrentState,
                      DWORD dwWin32ExitCode,
                      DWORD dwWaitHint)
{
    static DWORD dwCheckPoint = 1;

    // Fill in the SERVICE_STATUS structure.

    gSvcStatus.dwCurrentState = dwCurrentState;
    gSvcStatus.dwWin32ExitCode = dwWin32ExitCode;
    gSvcStatus.dwWaitHint = dwWaitHint;

    if (dwCurrentState == SERVICE_START_PENDING)
        gSvcStatus.dwControlsAccepted = 0;
    else gSvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;

    if ( (dwCurrentState == SERVICE_RUNNING) ||
           (dwCurrentState == SERVICE_STOPPED) )
        gSvcStatus.dwCheckPoint = 0;
    else gSvcStatus.dwCheckPoint = dwCheckPoint++;

    // Report the status of the service to the SCM.
    SetServiceStatus( gSvcStatusHandle, &gSvcStatus );
}

// TO COMPILE:
// c:\> g++ -c svchostdemo.cpp
// c:\> g++ -shared -o SvcHostDemo.dll svchostdemo.o

Community
  • 1
  • 1
Stryker2k2
  • 108
  • 9
  • Are you exporting the `ServiceMain()` function so `svchost.exe` can find it? It is not enough to mark the function as `WINAPI`, it needs to be exported explicitly, either with `__declspec(dllexport)` or `__export` or a `.def` file – Remy Lebeau May 05 '20 at 18:03
  • *gasp!* I think you might be on to something! Okay, I'll tinker around with that... brb. – Stryker2k2 May 05 '20 at 18:53
  • :( No dice. I added in __declspec (following the MSDN guidelines) as a DllExport definition and then tagged ServiceMain() with "DllExport WINAPI VOID ServiceMain(...)' and still nothing. – Stryker2k2 May 05 '20 at 20:25
  • But, did you *validate*, such as with `dumpbin`, that the function is being exported as just `"ServiceMain"` and not as, say, `"_ServiceMain@8"`? I take it that you have not worked with DLLs before, is that correct? – Remy Lebeau May 05 '20 at 20:30
  • You are right in your assumption that I'm new at DLLs. I now have 2-weeks of making my own DLLs. Thank you for suggesting validating the code! I just now put it into Ghidra and it is exporting as "__Z11ServiceMainmPPc@8". This has been a daunting two weeks but I've never been soo excited in my life to slam my head against a brick wall... I'm loving this stuff! – Stryker2k2 May 05 '20 at 20:41
  • [Exporting from a DLL Using DEF Files](https://learn.microsoft.com/en-us/cpp/build/exporting-from-a-dll-using-def-files?view=vs-2019), though that doc is geared for Visual C++, but I believe g++ also has an option to use a `.def` file, too. – Remy Lebeau May 05 '20 at 23:08

0 Answers0