headers: fail Build on missing native exports and assert MI/COM layouts (#2739)

Signed-off-by: Jan-Otto Kröpke <mail@jkroepke.de>
This commit is contained in:
Jan-Otto Kröpke
2026-10-16 02:32:29 +02:00
committed by GitHub
parent af2a7c3f6c
commit 2f5781ff13
43 changed files with 866 additions and 16 deletions
+7
View File
@@ -19,6 +19,7 @@ import (
"fmt"
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"github.com/prometheus-community/windows_exporter/internal/headers/win32"
"golang.org/x/sys/windows"
)
@@ -31,8 +32,14 @@ var (
procCMGetDeviceIDListSize = cfgmgr32.NewProc("CM_Get_Device_ID_List_SizeW")
procCMGetDevNodePropertyW = cfgmgr32.NewProc("CM_Get_DevNode_PropertyW")
procCMLocateDevNodeW = cfgmgr32.NewProc("CM_Locate_DevNodeW")
load = lazyproc.Once(cfgmgr32, procCMGetDeviceIDListW, procCMGetDeviceIDListSize, procCMGetDevNodePropertyW, procCMLocateDevNodeW)
)
// Load checks that cfgmgr32.dll exports every function of this package. Call
// it in Build: a missing export panics on the first call otherwise.
func Load() error { return load() }
func CMGetDeviceIDListSize(filter *win32.LPWSTR, size *uint32) error {
ret, _, _ := procCMGetDeviceIDListSize.Call(
uintptr(unsafe.Pointer(size)),
+14
View File
@@ -23,6 +23,7 @@ import (
"net"
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"golang.org/x/sys/windows"
)
@@ -35,8 +36,21 @@ var (
procDhcpV4EnumSubnetReservations = modDhcpServer.NewProc("DhcpV4EnumSubnetReservations")
procDhcpV4FailoverGetScopeStatistics = modDhcpServer.NewProc("DhcpV4FailoverGetScopeStatistics")
procDhcpGetMibInfoV5 = modDhcpServer.NewProc("DhcpGetMibInfoV5")
load = lazyproc.Once(modDhcpServer,
procDhcpGetSubnetInfo,
procDhcpGetSuperScopeInfoV4,
procDhcpRpcFreeMemory,
procDhcpV4EnumSubnetReservations,
procDhcpV4FailoverGetScopeStatistics,
procDhcpGetMibInfoV5,
)
)
// Load checks that dhcpsapi.dll exports every function of this package. Call
// it in Build: a missing export panics on the first call otherwise.
func Load() error { return load() }
func GetDHCPV4ScopeStatistics() ([]DHCPV4Scope, error) {
var mibInfo *DHCP_MIB_INFO_V5
+19
View File
@@ -19,6 +19,7 @@ import (
"fmt"
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"github.com/prometheus-community/windows_exporter/internal/headers/ntdll"
"golang.org/x/sys/windows"
)
@@ -30,8 +31,26 @@ var (
procD3DKMTQueryAdapterInfo = modGdi32.NewProc("D3DKMTQueryAdapterInfo")
procD3DKMTCloseAdapter = modGdi32.NewProc("D3DKMTCloseAdapter")
procD3DKMTEnumAdapters2 = modGdi32.NewProc("D3DKMTEnumAdapters2")
load = lazyproc.Once(modGdi32,
procD3DKMTOpenAdapterFromLuid,
procD3DKMTQueryAdapterInfo,
procD3DKMTCloseAdapter,
procD3DKMTEnumAdapters2,
)
)
// Load checks that gdi32.dll, and the ntdll functions this package uses,
// export every function of this package. Call it in Build: a missing export
// panics on the first call otherwise.
func Load() error {
if err := load(); err != nil {
return err
}
return ntdll.Load()
}
func D3DKMTOpenAdapterFromLuid(ptr *D3DKMT_OPENADAPTERFROMLUID) error {
ret, _, _ := procD3DKMTOpenAdapterFromLuid.Call(
uintptr(unsafe.Pointer(ptr)),
+13
View File
@@ -23,14 +23,27 @@ import (
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/hcs"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"github.com/prometheus-community/windows_exporter/internal/utils"
"golang.org/x/sys/windows"
)
// Load checks that vmcompute.dll, and the hcs functions this package uses,
// export every function of this package. Call it in Build: a missing export
// panics on the first call otherwise.
func Load() error {
if err := load(); err != nil {
return err
}
return hcs.Load()
}
//nolint:gochecknoglobals
var (
modvmcompute = windows.NewLazySystemDLL("vmcompute.dll")
procHNSCall = modvmcompute.NewProc("HNSCall")
load = lazyproc.Once(modvmcompute, procHNSCall)
hcnBodyEmpty = utils.Must(windows.UTF16PtrFromString(""))
hcnMethodGet = utils.Must(windows.UTF16PtrFromString("GET"))
+15
View File
@@ -22,6 +22,7 @@ import (
"fmt"
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"golang.org/x/sys/windows"
)
@@ -36,8 +37,22 @@ var (
procHcsOpenComputeSystem = modComputeCore.NewProc("HcsOpenComputeSystem")
procHcsGetComputeSystemProperties = modComputeCore.NewProc("HcsGetComputeSystemProperties")
procHcsCloseComputeSystem = modComputeCore.NewProc("HcsCloseComputeSystem")
load = lazyproc.Once(modComputeCore,
procHcsCreateOperation,
procHcsWaitForOperationResult,
procHcsCloseOperation,
procHcsEnumerateComputeSystems,
procHcsOpenComputeSystem,
procHcsGetComputeSystemProperties,
procHcsCloseComputeSystem,
)
)
// Load checks that computecore.dll exports every function of this package.
// Call it in Build: a missing export panics on the first call otherwise.
func Load() error { return load() }
// CreateOperation creates a new operation.
//
// HcsCreateOperation returns the operation handle, or NULL on failure.
+7
View File
@@ -22,6 +22,7 @@ import (
"fmt"
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"golang.org/x/sys/windows"
)
@@ -29,8 +30,14 @@ import (
var (
modiphlpapi = windows.NewLazySystemDLL("iphlpapi.dll")
procGetExtendedTcpTable = modiphlpapi.NewProc("GetExtendedTcpTable")
load = lazyproc.Once(modiphlpapi, procGetExtendedTcpTable)
)
// Load checks that iphlpapi.dll exports every function of this package. Call
// it in Build: a missing export panics on the first call otherwise.
func Load() error { return load() }
func GetTCPConnectionStates(family uint32) (map[MIB_TCP_STATE]uint32, error) {
stateCounts := make(map[MIB_TCP_STATE]uint32)
+14
View File
@@ -20,6 +20,7 @@ package kernel32
import (
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"golang.org/x/sys/windows"
)
@@ -31,8 +32,21 @@ var (
procKernelLocalFileTimeToFileTime = modkernel32.NewProc("LocalFileTimeToFileTime")
procOpenJobObject = modkernel32.NewProc("OpenJobObjectW")
procIsProcessInJob = modkernel32.NewProc("IsProcessInJob")
// GetDiskSpaceInformationW is optional and checked by GetDiskSpaceInformation.
load = lazyproc.Once(modkernel32,
procGetDynamicTimeZoneInformationSys,
procKernelLocalFileTimeToFileTime,
procOpenJobObject,
procIsProcessInJob,
)
)
// Load checks that kernel32.dll exports every function this package calls
// without a check of its own. Call it in Build: a missing export panics on
// the first call otherwise.
func Load() error { return load() }
// SYSTEMTIME contains a date and time.
// 📑 https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime
type SYSTEMTIME struct {
@@ -0,0 +1,85 @@
// SPDX-License-Identifier: Apache-2.0
//
// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build windows
package lazyproc_test
import (
"os"
"path/filepath"
"testing"
"github.com/prometheus-community/windows_exporter/internal/headers/cfgmgr32"
"github.com/prometheus-community/windows_exporter/internal/headers/dhcpsapi"
"github.com/prometheus-community/windows_exporter/internal/headers/gdi32"
"github.com/prometheus-community/windows_exporter/internal/headers/hcn"
"github.com/prometheus-community/windows_exporter/internal/headers/hcs"
"github.com/prometheus-community/windows_exporter/internal/headers/iphlpapi"
"github.com/prometheus-community/windows_exporter/internal/headers/kernel32"
"github.com/prometheus-community/windows_exporter/internal/headers/ntdll"
"github.com/prometheus-community/windows_exporter/internal/headers/psapi"
"github.com/prometheus-community/windows_exporter/internal/headers/slc"
"github.com/prometheus-community/windows_exporter/internal/headers/sysinfoapi"
"github.com/prometheus-community/windows_exporter/internal/headers/winspool"
"github.com/prometheus-community/windows_exporter/internal/headers/wtsapi32"
"github.com/prometheus-community/windows_exporter/internal/pdh"
"github.com/stretchr/testify/require"
"golang.org/x/sys/windows"
)
// TestBindingsLoad checks the export names of every binding package against
// the DLLs of this host. A DLL that belongs to an optional Windows feature
// skips its binding when the DLL is not installed.
func TestBindingsLoad(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name string
load func() error
// optionalDLL is set for DLLs of optional Windows features.
optionalDLL string
}{
{name: "cfgmgr32", load: cfgmgr32.Load},
{name: "dhcpsapi", load: dhcpsapi.Load, optionalDLL: "dhcpsapi.dll"},
{name: "gdi32", load: gdi32.Load},
{name: "hcn", load: hcn.Load, optionalDLL: "vmcompute.dll"},
{name: "hcs", load: hcs.Load, optionalDLL: "computecore.dll"},
{name: "iphlpapi", load: iphlpapi.Load},
{name: "kernel32", load: kernel32.Load},
{name: "ntdll", load: ntdll.Load},
{name: "psapi", load: psapi.Load},
{name: "slc", load: slc.Load},
{name: "sysinfoapi", load: sysinfoapi.Load},
{name: "winspool", load: winspool.Load},
{name: "wtsapi32", load: wtsapi32.Load},
{name: "pdh", load: pdh.Load},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if tc.optionalDLL != "" {
systemDirectory, err := windows.GetSystemDirectory()
require.NoError(t, err)
if _, err := os.Stat(filepath.Join(systemDirectory, tc.optionalDLL)); err != nil {
t.Skipf("%s is not installed: %v", tc.optionalDLL, err)
}
}
require.NoError(t, tc.load())
})
}
}
+95
View File
@@ -0,0 +1,95 @@
// SPDX-License-Identifier: Apache-2.0
//
// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build windows
// Package lazyproc checks that lazily loaded native functions exist.
//
// windows.LazyProc.Call panics when its DLL or export is missing, e.g. on a
// Windows version or edition without the subsystem. A binding package lists
// the functions it calls without a check of its own in a Load function built
// with [Once], and collectors call it in Build, so a missing export fails
// Build instead of panicking on the first scrape.
package lazyproc
import (
"errors"
"fmt"
"strings"
"sync"
"golang.org/x/sys/windows"
)
// Error reports a missing DLL or missing exports. It matches
// [errors.ErrUnsupported] and has no other cause, so a collector that fails
// Build with it is skipped as an unavailable subsystem: the loader errors,
// e.g. ERROR_MOD_NOT_FOUND, are only kept as text and in Missing.
type Error struct {
// DLL is the name of the DLL.
DLL string
// Missing holds the error of the DLL, if it could not be loaded, or of
// each missing export.
Missing []error
}
func (e *Error) Error() string {
var message strings.Builder
fmt.Fprintf(&message, "%s: %s", errors.ErrUnsupported, e.DLL)
for _, err := range e.Missing {
message.WriteString(": ")
message.WriteString(err.Error())
}
return message.String()
}
// Is reports whether target is [errors.ErrUnsupported].
func (e *Error) Is(target error) bool {
return target == errors.ErrUnsupported
}
// Find loads dll and every proc, which must belong to dll. It returns nil if
// all of them exist, and otherwise an [*Error] that names the missing DLL or
// each missing export.
func Find(dll *windows.LazyDLL, procs ...*windows.LazyProc) error {
if err := dll.Load(); err != nil {
return &Error{DLL: dll.Name, Missing: []error{err}}
}
var missing []error
for _, proc := range procs {
if err := proc.Find(); err != nil {
missing = append(missing, err)
}
}
if len(missing) == 0 {
return nil
}
return &Error{DLL: dll.Name, Missing: missing}
}
// Once returns a function that runs [Find] once and then returns its result.
// A DLL or export that is missing stays missing for the life of the process.
func Once(dll *windows.LazyDLL, procs ...*windows.LazyProc) func() error {
return sync.OnceValue(func() error {
return Find(dll, procs...)
})
}
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: Apache-2.0
//
// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build windows
package lazyproc_test
import (
"errors"
"strings"
"testing"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"github.com/stretchr/testify/require"
"golang.org/x/sys/windows"
)
func TestFind(t *testing.T) {
t.Parallel()
kernel32 := windows.NewLazySystemDLL("kernel32.dll")
missingDLL := windows.NewLazySystemDLL("windows_exporter_missing.dll")
t.Run("all present", func(t *testing.T) {
t.Parallel()
require.NoError(t, lazyproc.Find(kernel32, kernel32.NewProc("GetTickCount64"), kernel32.NewProc("GetSystemInfo")))
require.NoError(t, lazyproc.Find(kernel32))
})
t.Run("missing export", func(t *testing.T) {
t.Parallel()
err := lazyproc.Find(kernel32, kernel32.NewProc("GetTickCount64"), kernel32.NewProc("WindowsExporterMissingExport"))
require.ErrorIs(t, err, errors.ErrUnsupported)
require.ErrorContains(t, err, "WindowsExporterMissingExport")
})
t.Run("missing DLL is reported once", func(t *testing.T) {
t.Parallel()
err := lazyproc.Find(missingDLL, missingDLL.NewProc("A"), missingDLL.NewProc("B"))
require.ErrorIs(t, err, errors.ErrUnsupported)
require.Equal(t, 1, strings.Count(err.Error(), "windows_exporter_missing.dll"), err.Error())
// The loader error stays text only, so the error has a single cause.
require.NotErrorIs(t, err, windows.ERROR_MOD_NOT_FOUND)
var lazyErr *lazyproc.Error
require.ErrorAs(t, err, &lazyErr)
require.Equal(t, "windows_exporter_missing.dll", lazyErr.DLL)
require.Len(t, lazyErr.Missing, 1)
})
t.Run("Once", func(t *testing.T) {
t.Parallel()
load := lazyproc.Once(kernel32, kernel32.NewProc("WindowsExporterMissingExport"))
first := load()
require.ErrorIs(t, first, errors.ErrUnsupported)
// The cached error is returned again.
require.Same(t, first, load())
})
}
+7
View File
@@ -18,6 +18,7 @@
package ntdll
import (
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"golang.org/x/sys/windows"
)
@@ -25,8 +26,14 @@ import (
var (
modNtdll = windows.NewLazySystemDLL("ntdll.dll")
procRtlNtStatusToDosError = modNtdll.NewProc("RtlNtStatusToDosError")
load = lazyproc.Once(modNtdll, procRtlNtStatusToDosError)
)
// Load checks that ntdll.dll exports every function of this package. Call it
// in Build: a missing export panics on the first call otherwise.
func Load() error { return load() }
func RtlNtStatusToDosError(status uintptr) error {
ret, _, _ := procRtlNtStatusToDosError.Call(status)
if ret == 0 {
+7
View File
@@ -20,6 +20,7 @@ package psapi
import (
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"golang.org/x/sys/windows"
)
@@ -46,8 +47,14 @@ type PerformanceInformation struct {
var (
psapi = windows.NewLazySystemDLL("psapi.dll")
procGetPerformanceInfo = psapi.NewProc("GetPerformanceInfo")
load = lazyproc.Once(psapi, procGetPerformanceInfo)
)
// Load checks that psapi.dll exports every function of this package. Call it
// in Build: a missing export panics on the first call otherwise.
func Load() error { return load() }
// GetPerformanceInfo returns the dereferenced version of GetLPPerformanceInfo.
func GetPerformanceInfo() (PerformanceInformation, error) {
var lppi PerformanceInformation
+7
View File
@@ -21,6 +21,7 @@ import (
"errors"
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"golang.org/x/sys/windows"
)
@@ -28,8 +29,14 @@ import (
var (
slc = windows.NewLazySystemDLL("slc.dll")
procSLIsWindowsGenuineLocal = slc.NewProc("SLIsWindowsGenuineLocal")
load = lazyproc.Once(slc, procSLIsWindowsGenuineLocal)
)
// Load checks that slc.dll exports every function of this package. Call it in
// Build: a missing export panics on the first call otherwise.
func Load() error { return load() }
// SL_GENUINE_STATE enumeration
//
// https://learn.microsoft.com/en-us/windows/win32/api/slpublic/ne-slpublic-sl_genuine_state
+12
View File
@@ -21,6 +21,7 @@ import (
"unicode/utf16"
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"golang.org/x/sys/windows"
)
@@ -121,8 +122,19 @@ var (
procGetSystemInfo = kernel32.NewProc("GetSystemInfo")
procGlobalMemoryStatusEx = kernel32.NewProc("GlobalMemoryStatusEx")
procGetComputerNameExW = kernel32.NewProc("GetComputerNameExW")
load = lazyproc.Once(kernel32,
procGetSystemInfo,
procGlobalMemoryStatusEx,
procGetComputerNameExW,
procGetSystemFirmwareTable,
)
)
// Load checks that kernel32.dll exports every function of this package. Call
// it in Build: a missing export panics on the first call otherwise.
func Load() error { return load() }
// GlobalMemoryStatusEx retrieves information about the system's current usage of both physical and virtual memory.
// https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-globalmemorystatusex
func GlobalMemoryStatusEx() (MemoryStatus, error) {
+7
View File
@@ -27,6 +27,7 @@ import (
"fmt"
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"golang.org/x/sys/windows"
)
@@ -38,8 +39,14 @@ var (
procOpenPrinterW = modWinspool.NewProc("OpenPrinterW")
procClosePrinter = modWinspool.NewProc("ClosePrinter")
procEnumJobsW = modWinspool.NewProc("EnumJobsW")
load = lazyproc.Once(modWinspool, procEnumPrintersW, procOpenPrinterW, procClosePrinter, procEnumJobsW)
)
// Load checks that winspool.drv exports every function of this package. Call
// it in Build: a missing export panics on the first call otherwise.
func Load() error { return load() }
// EnumPrinters returns the printers selected by flags, a combination of PRINTER_ENUM_* values.
func EnumPrinters(flags uint32) ([]Printer, error) {
buf, count, err := enum(func(buf *byte, size uint32, needed, returned *uint32) (uintptr, error) {
+7
View File
@@ -22,9 +22,14 @@ import (
"log/slog"
"unsafe"
"github.com/prometheus-community/windows_exporter/internal/headers/lazyproc"
"golang.org/x/sys/windows"
)
// Load checks that wtsapi32.dll exports every function of this package. Call
// it in Build: a missing export panics on the first call otherwise.
func Load() error { return load() }
type WTSTypeClass int
// The valid values for the WTSTypeClass enumeration.
@@ -107,6 +112,8 @@ var (
procWTSFreeMemoryEx = wtsapi32.NewProc("WTSFreeMemoryExW")
procWTSCloseServer = wtsapi32.NewProc("WTSCloseServer")
load = lazyproc.Once(wtsapi32, procWTSOpenServerEx, procWTSEnumerateSessionsEx, procWTSFreeMemoryEx, procWTSCloseServer)
WTSSessionStates = map[WTSConnectState]string{
wtsActive: "active",
wtsConnected: "connected",