golang.zx2c4.com/wireguard/windows@v0.5.4-0.20230123132234-dcc0eb72a04b/elevate/loader.go (about)

     1  /* SPDX-License-Identifier: MIT
     2   *
     3   * Copyright (C) 2019-2022 WireGuard LLC. All Rights Reserved.
     4   */
     5  
     6  package elevate
     7  
     8  import (
     9  	"unsafe"
    10  
    11  	"golang.org/x/sys/windows"
    12  )
    13  
    14  /* We could use the undocumented LdrFindEntryForAddress function instead, but that's undocumented, and we're trying
    15   * to be as rock-solid as possible here. */
    16  func findCurrentDataTableEntry() (entry *windows.LDR_DATA_TABLE_ENTRY, err error) {
    17  	peb := windows.RtlGetCurrentPeb()
    18  	if peb == nil || peb.Ldr == nil {
    19  		err = windows.ERROR_INVALID_ADDRESS
    20  		return
    21  	}
    22  	for cur := peb.Ldr.InMemoryOrderModuleList.Flink; cur != &peb.Ldr.InMemoryOrderModuleList; cur = cur.Flink {
    23  		entry = (*windows.LDR_DATA_TABLE_ENTRY)(unsafe.Pointer(uintptr(unsafe.Pointer(cur)) - unsafe.Offsetof(windows.LDR_DATA_TABLE_ENTRY{}.InMemoryOrderLinks)))
    24  		if entry.DllBase == peb.ImageBaseAddress {
    25  			return
    26  		}
    27  	}
    28  	entry = nil
    29  	err = windows.ERROR_OBJECT_NOT_FOUND
    30  	return
    31  }