Introducing SvcHostify: Simplify Hosting Custom DLL Services

Have you ever struggled with hosting your own DLLs as Windows services using svchost.exe? Many developers face challenges due to the undocumented and restrictive nature of svchost.exe. That’s where SvcHostify comes in—a lightweight, open-source tool designed to make hosting custom DLL services easier than ever.

Why SvcHostify?

SvcHostify eliminates the complexity of writing svchost-compatible services. Whether you’re coding in Java, C#, or C++, this tool handles the heavy lifting, letting you focus on your application logic. No more worries about C-style exports or system quirks.

  • Support for multiple languages: Build services in Java, C#, or C++ without worrying about low-level plumbing.
  • Two hosting modes:
    • SvcHost Mode: For academic/research purposes.
    • Standalone Mode: Run services using rundll32.exe—perfect for production.
  • Streamlined JSON configuration: Define service metadata, runtime behavior, and logging in one simple file.

What Can You Do with SvcHostify?

  • Host Java applications via JVM integration.
  • Run .NET DLLs as in-process COM servers.
  • Manage lightweight C++ services by exporting minimalistic C-style functions.

Features You’ll Love

  1. Effortless Service Management:
    Install and uninstall services in seconds with simple commands.
rundll32 svchostify.dll invoke -i -c <CONFIG_FILE>
rundll32 svchostify.dll invoke -u -c <CONFIG_FILE>

  1. Centralized Logging:
    Consolidates logs from stdout, stderr, and other streams into a single file, making debugging a breeze.
  2. Production-Ready Standalone Mode:
    Distribute your service easily without needing svchost.exe.
  3. Open Source Flexibility:
    Modify, enhance, and adapt SvcHostify for your unique use cases—licensed under MIT.

Sample Use Case: Hosting a Java Service

Here’s an example JSON configuration for running a Java-based service:

{
  "workerType": "jvm",
  "name": "MyJavaService",
  "displayName": "My Java Test Service",
  "context": "path/to/your/app.jar",
  "accountType": "networkService",
  "standalone": true,
  "logger": {
    "basePath": "logs/java.log",
    "maxSize": "10 MiB",
    "maxFiles": 5
  }
}

A few lines of JSON are all it takes to spin up your service!

Who Should Use SvcHostify?

  • Developers who need a quick way to deploy custom DLL services on Windows.
  • Organizations looking to simplify the deployment of internal tools and applications.
  • Hobbyists and researchers exploring the possibilities of Windows Service customization.

Get Started Today!

Visit the SvcHostify GitHub Repository to download the latest release, check out detailed documentation, and dive into sample projects.

Simplify your Windows Service development with SvcHostify—your next DLL-hosting project just got easier!

Windows String Representations and Simple Conversions via __bstr_t

The Windows NT kernel (from WinNT to Windows 11) internally uses UTF-16 strings by default, including Windows Drivers, Native Applications and COM clients and servers, etc. All other common encodings like UTF-8, GBK, GB18030, BIG-5 should always be converted to UTF-16 before invocations to the kernel functions within ntdll.dll.

There is a compatible layer upon the kernel layer, which is called Win32 API, a huge heritage left by the Win9X series. Win32 API is a family of functions for programmers to communicate with the operating system and hardware conveniently. Microsoft keeps this compatibility on the Windows NT Kernel so that most of the Win32 functions are still remaining unchanged and ABI-compatible. For example the CreateFile function does exist from Windows 98 to Windows 11. That is unbelievable because a Linux distribution may break any API in a minor update!

HANDLE CreateFile(
  [in]           LPCSTR                lpFileName,
  [in]           DWORD                 dwDesiredAccess,
  [in]           DWORD                 dwShareMode,
  [in, optional] LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  [in]           DWORD                 dwCreationDisposition,
  [in]           DWORD                 dwFlagsAndAttributes,
  [in, optional] HANDLE                hTemplateFile
);

Some challenges started to occur. The Unicode Standard was then generally accepted by OS vendors after Win9X was released while the Win9X was still using the ANSI encoding or some multi-byte encoding in the terminal country like GB2312 and BIG-5. The Windows NT Kernel chose the UTF-16 as its kernel string representations that hindered the working progress of compatibility.

To resolve this issue, Microsoft’s talented engineers decided to create duplicates of the corresponding old Win32 APIs. The only difference of these two versions is the string types: LPCSTR vs LPCWSTR, the aliases of const char* and const wchar_t* in C++. The former represents the ANSI, and the latter stores a UTF-16 encoded string. To distinguish the mangled names at the C ABI level, the developers simply added a single-word suffix for the function: -A for the ANSI version and -W for the Unicode version. It provides much flexibility for users to call any of them in their projects.

BOOL DeleteFileA(
  [in] LPCSTR lpFileName
);

BOOL DeleteFileW(
  [in] LPCWSTR lpFileName
);

Generally speaking, the encoding API MultibyteToWideChar and WideCharToMultiByte are the usual way to reach the goal of interoperability for user-mode programs using different internal string representations on Windows.

int WideCharToMultiByte(
  [in]            UINT                               CodePage,
  [in]            DWORD                              dwFlags,
  [in]            _In_NLS_string_(cchWideChar)LPCWCH lpWideCharStr,
  [in]            int                                cchWideChar,
  [out, optional] LPSTR                              lpMultiByteStr,
  [in]            int                                cbMultiByte,
  [in, optional]  LPCCH                              lpDefaultChar,
  [out, optional] LPBOOL                             lpUsedDefaultChar
);

int MultiByteToWideChar(
  [in]            UINT                              CodePage,
  [in]            DWORD                             dwFlags,
  [in]            _In_NLS_string_(cbMultiByte)LPCCH lpMultiByteStr,
  [in]            int                               cbMultiByte,
  [out, optional] LPWSTR                            lpWideCharStr,
  [in]            int                               cchWideChar
);

It requires two calls to each function for one single conversion, the first call to calculate the buffer size and the second to perform the actual conversion. There is a simpler method to behave equivalently, that is to say, via the __bstr_t class that is supplied within the compiler’s COM support.

The COM always uses UTF-16 strings as mentioned above and the BSTR type (that is wchar_t* with some extra header) is the standard string type of COM. MSVC has native support for BSTR called __bstr_t, an encapsulation of the BSTR data type, providing a simplified version compared with the general approach.

A faster way to do encoding conversions is to instantiate an object of _bstr_t using the constructor based on the signature const char*. This overload takes an ANSI string and converts it to a UTF-16 string immediately and the _bstr_t has a const wchar_t* operator() to do the implicit cast and vice versa.

#include <string>
#include <string_view>

#include <comutil.h>

const std::string str{ "Hello some 汉字 characters" };
const _bstr_t wide_str{ str.c_str() };
const std::wstring_view{ wide_str };

#include <string>
#include <string_view>

#include <comutil.h>

const std::wstring str{ L"一些宽字符,逆向转换" };
const _bstr_t wide_str{ str.c_str() };
const std::string_view{ wide_str };

Inside std::source_location

Since C++20, the new revolutionary standard has introduced a meta class named std::source_location which provides information about the current line number, file name and function name of the executing context. This new class is included in a standalone header <source_location> and also a better alternative to the old methods like __LINE__ and __FILE__.

std::source_location shows some magic mechanism to make an access to the code context without any macro expansions, as if it ‘knows’ the compile-time names and numbers where it is placed, as follows:

#include <print>
#include <source_location>

namespace {
  void print_loc(const std::source_location& loc) {
    std::print("File: {}, Position: ({},{}), Function: {}\n",
      loc.file_name(), loc.line(), loc.column(), loc.function_name()
    );
  }
}

struct foo {
  foo(std::source_location loc = std::source_location::current()) {
    print_loc(loc);
  }
  
  void baz(int number, std::source_location loc = std::source_location::current()) const {
    print_loc(loc);
  }
};

int main() {
  const foo obj;
  
  obj.baz(1);
}

The output of the function name is implementation-defined, due to the different name mangling rules among GCC, Clang and MSVC. Both GCC and Clang respect the Itanium ABI, and however Microsoft maintains its unique and uniform ABI on Windows known as the MSVC ABI or Windows COM ABI.

File: /app/example.cpp, Position: (23,13), Function: int main()
File: /app/example.cpp, Position: (25,10), Function: int main()

GCC is licensed under the GNU General Public License (GPL), specifically the GPLv3 with a special exception. Microsoft open-sourced its STL implementation on GitHub, with an Apache-2.0-with-LLVM-exception license. The latest GCC codebase defines a new built-in function named __builtin_source_location to generate information of the call site directly. In addition, MSVC’s STL continues to use existing built-in functions such as __builtin_LINE, __builtin_COLUMN, __builtin_FILE, __builtin_FUNCTION/__builtin_FUNCSIG that has been introduced in older versions.

 // [support.srcloc.cons], creation
static consteval source_location
current(__builtin_ret_type __p = __builtin_source_location()) noexcept {
  source_location __ret;
  __ret._M_impl = static_cast <const __impl*>(__p);
  return __ret;
}

_NODISCARD static consteval source_location current(const uint_least32_t _Line_ = __builtin_LINE(),
        const uint_least32_t _Column_ = __builtin_COLUMN(), const char* const _File_ = __builtin_FILE(),
#if _USE_DETAILED_FUNCTION_NAME_IN_SOURCE_LOCATION
        const char* const _Function_ = __builtin_FUNCSIG()
#else // ^^^ detailed / basic vvv
        const char* const _Function_ = __builtin_FUNCTION()
#endif // ^^^ basic ^^^
            ) noexcept {
  source_location _Result{};
  _Result._Line     = _Line_;
  _Result._Column   = _Column_;
  _Result._File     = _File_;
  _Result._Function = _Function_;
  return _Result;
}

When using an early version of the compiler that does not contain <source_location>, writing a custom source_location class with similar functions whose values refer to the evaluation results of these built-in functions is an acceptable consideration. Literally, GCC does provide the same functions as MSVC in GCC 10 without full support of the C++20 Standard.