Source file src/runtime/cgo/library_windows.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build goexperiment.cgobindings && windows && !msan && !tsan
     6  
     7  package cgo
     8  
     9  import (
    10  	"errors"
    11  	"internal/strconv"
    12  	"internal/stringslite"
    13  	"runtime"
    14  	"unsafe"
    15  )
    16  
    17  //go:cgo_import_dynamic _cgo_LoadLibraryW LoadLibraryW%1 "kernel32.dll"
    18  //go:linkname _cgo_LoadLibraryW _cgo_LoadLibraryW
    19  var _cgo_LoadLibraryW unsafe.Pointer
    20  
    21  //go:cgo_import_dynamic _cgo_GetProcAddress GetProcAddress%2 "kernel32.dll"
    22  //go:linkname _cgo_GetProcAddress _cgo_GetProcAddress
    23  var _cgo_GetProcAddress unsafe.Pointer
    24  
    25  func dlopen(path string) (uintptr, error) {
    26  	if stringslite.IndexByte(path, 0) >= 0 {
    27  		return 0, errors.New("cgo: dlopen: path contains NUL byte")
    28  	}
    29  	wpath := utf16FromString(path)
    30  
    31  	ret, errno := cgocallErr(uintptr(_cgo_LoadLibraryW), uintptr(unsafe.Pointer(&wpath[0])), 0, 0, 0, 0, 0)
    32  	runtime.KeepAlive(wpath)
    33  	if ret == 0 {
    34  		return 0, errors.New("cgo: dlopen: " + path + ": error " + strconv.FormatUint(uint64(errno), 10))
    35  	}
    36  	return ret, nil
    37  }
    38  
    39  func dlsym(h uintptr, name string) (unsafe.Pointer, string) {
    40  	if stringslite.IndexByte(name, 0) >= 0 {
    41  		return nil, "symbol name contains NUL byte"
    42  	}
    43  	cname := append([]byte(name), 0)
    44  
    45  	ret, errno := cgocallErr(uintptr(_cgo_GetProcAddress), h, uintptr(unsafe.Pointer(&cname[0])), 0, 0, 0, 0)
    46  	runtime.KeepAlive(cname)
    47  	if ret == 0 {
    48  		return nil, "error " + strconv.FormatUint(uint64(errno), 10)
    49  	}
    50  	return *(*unsafe.Pointer)(unsafe.Pointer(&ret)), ""
    51  }
    52  
    53  func utf16FromString(s string) []uint16 {
    54  	const (
    55  		replacementChar = '\uFFFD'
    56  		maxRune         = '\U0010FFFF'
    57  		surr1           = 0xd800
    58  		surr2           = 0xdc00
    59  		surr3           = 0xe000
    60  		surrSelf        = 0x10000
    61  	)
    62  	buf := make([]uint16, 0, len(s)+1)
    63  	for _, r := range s {
    64  		switch {
    65  		case 0 <= r && r < surr1, surr3 <= r && r < surrSelf:
    66  			buf = append(buf, uint16(r))
    67  		case surrSelf <= r && r <= maxRune:
    68  			r -= surrSelf
    69  			buf = append(buf, uint16(surr1+(r>>10)&0x3ff), uint16(surr2+r&0x3ff))
    70  		default:
    71  			buf = append(buf, replacementChar)
    72  		}
    73  	}
    74  	return append(buf, 0)
    75  }
    76  

View as plain text