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

     1  //go:build !load_wgnt_from_rsrc
     2  
     3  /* SPDX-License-Identifier: MIT
     4   *
     5   * Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
     6   */
     7  
     8  package driver
     9  
    10  import (
    11  	"fmt"
    12  	"sync"
    13  	"sync/atomic"
    14  	"unsafe"
    15  
    16  	"golang.org/x/sys/windows"
    17  )
    18  
    19  type lazyDLL struct {
    20  	Name   string
    21  	Base   windows.Handle
    22  	mu     sync.Mutex
    23  	module windows.Handle
    24  	onLoad func(d *lazyDLL)
    25  }
    26  
    27  func (d *lazyDLL) Load() error {
    28  	if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&d.module))) != nil {
    29  		return nil
    30  	}
    31  	d.mu.Lock()
    32  	defer d.mu.Unlock()
    33  	if d.module != 0 {
    34  		return nil
    35  	}
    36  
    37  	const (
    38  		LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x00000200
    39  		LOAD_LIBRARY_SEARCH_SYSTEM32        = 0x00000800
    40  	)
    41  	module, err := windows.LoadLibraryEx(d.Name, 0, LOAD_LIBRARY_SEARCH_APPLICATION_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32)
    42  	if err != nil {
    43  		return fmt.Errorf("Unable to load library: %w", err)
    44  	}
    45  	d.Base = module
    46  
    47  	atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&d.module)), unsafe.Pointer(module))
    48  	if d.onLoad != nil {
    49  		d.onLoad(d)
    50  	}
    51  	return nil
    52  }
    53  
    54  func (p *lazyProc) nameToAddr() (uintptr, error) {
    55  	return windows.GetProcAddress(p.dll.module, p.Name)
    56  }