1 // Copyright 2011 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.
14 // We need to use LoadLibrary and GetProcAddress from the Go runtime, because
15 // the these symbols are loaded by the system linker and are required to
16 // dynamically load additional symbols. Note that in the Go runtime, these
17 // return syscall.Handle and syscall.Errno, but these are the same, in fact,
18 // as windows.Handle and windows.Errno, and we intend to keep these the same.
20 //go:linkname syscall_loadlibrary syscall.loadlibrary
21 func syscall_loadlibrary(filename *uint16) (handle Handle, err Errno)
23 //go:linkname syscall_getprocaddress syscall.getprocaddress
24 func syscall_getprocaddress(handle Handle, procname *uint8) (proc uintptr, err Errno)
26 // DLLError describes reasons for DLL load failures.
27 type DLLError struct {
33 func (e *DLLError) Error() string { return e.Msg }
35 func (e *DLLError) Unwrap() error { return e.Err }
37 // A DLL implements access to a single DLL.
43 // LoadDLL loads DLL file into memory.
45 // Warning: using LoadDLL without an absolute path name is subject to
46 // DLL preloading attacks. To safely load a system DLL, use LazyDLL
47 // with System set to true, or use LoadLibraryEx directly.
48 func LoadDLL(name string) (dll *DLL, err error) {
49 namep, err := UTF16PtrFromString(name)
53 h, e := syscall_loadlibrary(namep)
55 return nil, &DLLError{
58 Msg: "Failed to load " + name + ": " + e.Error(),
68 // MustLoadDLL is like LoadDLL but panics if load operation failes.
69 func MustLoadDLL(name string) *DLL {
77 // FindProc searches DLL d for procedure named name and returns *Proc
78 // if found. It returns an error if search fails.
79 func (d *DLL) FindProc(name string) (proc *Proc, err error) {
80 namep, err := BytePtrFromString(name)
84 a, e := syscall_getprocaddress(d.Handle, namep)
86 return nil, &DLLError{
89 Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(),
100 // MustFindProc is like FindProc but panics if search fails.
101 func (d *DLL) MustFindProc(name string) *Proc {
102 p, e := d.FindProc(name)
109 // FindProcByOrdinal searches DLL d for procedure by ordinal and returns *Proc
110 // if found. It returns an error if search fails.
111 func (d *DLL) FindProcByOrdinal(ordinal uintptr) (proc *Proc, err error) {
112 a, e := GetProcAddressByOrdinal(d.Handle, ordinal)
113 name := "#" + itoa(int(ordinal))
115 return nil, &DLLError{
118 Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(),
129 // MustFindProcByOrdinal is like FindProcByOrdinal but panics if search fails.
130 func (d *DLL) MustFindProcByOrdinal(ordinal uintptr) *Proc {
131 p, e := d.FindProcByOrdinal(ordinal)
138 // Release unloads DLL d from memory.
139 func (d *DLL) Release() (err error) {
140 return FreeLibrary(d.Handle)
143 // A Proc implements access to a procedure inside a DLL.
150 // Addr returns the address of the procedure represented by p.
151 // The return value can be passed to Syscall to run the procedure.
152 func (p *Proc) Addr() uintptr {
158 // Call executes procedure p with arguments a. It will panic, if more than 15 arguments
161 // The returned error is always non-nil, constructed from the result of GetLastError.
162 // Callers must inspect the primary return value to decide whether an error occurred
163 // (according to the semantics of the specific function being called) before consulting
164 // the error. The error will be guaranteed to contain windows.Errno.
165 func (p *Proc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) {
168 return syscall.Syscall(p.Addr(), uintptr(len(a)), 0, 0, 0)
170 return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], 0, 0)
172 return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], 0)
174 return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], a[2])
176 return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], 0, 0)
178 return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], 0)
180 return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5])
182 return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], 0, 0)
184 return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], 0)
186 return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8])
188 return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], 0, 0)
190 return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], 0)
192 return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11])
194 return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], 0, 0)
196 return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], 0)
198 return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14])
200 panic("Call " + p.Name + " with too many arguments " + itoa(len(a)) + ".")
204 // A LazyDLL implements access to a single DLL.
205 // It will delay the load of the DLL until the first
206 // call to its Handle method or to one of its
207 // LazyProc's Addr method.
208 type LazyDLL struct {
211 // System determines whether the DLL must be loaded from the
212 // Windows System directory, bypassing the normal DLL search
217 dll *DLL // non nil once DLL is loaded
220 // Load loads DLL file d.Name into memory. It returns an error if fails.
221 // Load will not try to load DLL, if it is already loaded into memory.
222 func (d *LazyDLL) Load() error {
223 // Non-racy version of:
225 if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll))) != nil {
234 // kernel32.dll is special, since it's where LoadLibraryEx comes from.
235 // The kernel already special-cases its name, so it's always
236 // loaded from system32.
239 if d.Name == "kernel32.dll" {
240 dll, err = LoadDLL(d.Name)
242 dll, err = loadLibraryEx(d.Name, d.System)
248 // Non-racy version of:
250 atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll)), unsafe.Pointer(dll))
254 // mustLoad is like Load but panics if search fails.
255 func (d *LazyDLL) mustLoad() {
262 // Handle returns d's module handle.
263 func (d *LazyDLL) Handle() uintptr {
265 return uintptr(d.dll.Handle)
268 // NewProc returns a LazyProc for accessing the named procedure in the DLL d.
269 func (d *LazyDLL) NewProc(name string) *LazyProc {
270 return &LazyProc{l: d, Name: name}
273 // NewLazyDLL creates new LazyDLL associated with DLL file.
274 func NewLazyDLL(name string) *LazyDLL {
275 return &LazyDLL{Name: name}
278 // NewLazySystemDLL is like NewLazyDLL, but will only
279 // search Windows System directory for the DLL if name is
280 // a base name (like "advapi32.dll").
281 func NewLazySystemDLL(name string) *LazyDLL {
282 return &LazyDLL{Name: name, System: true}
285 // A LazyProc implements access to a procedure inside a LazyDLL.
286 // It delays the lookup until the Addr method is called.
287 type LazyProc struct {
295 // Find searches DLL for procedure named p.Name. It returns
296 // an error if search fails. Find will not search procedure,
297 // if it is already found and loaded into memory.
298 func (p *LazyProc) Find() error {
299 // Non-racy version of:
300 // if p.proc == nil {
301 if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc))) == nil {
309 proc, e := p.l.dll.FindProc(p.Name)
313 // Non-racy version of:
315 atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc)), unsafe.Pointer(proc))
321 // mustFind is like Find but panics if search fails.
322 func (p *LazyProc) mustFind() {
329 // Addr returns the address of the procedure represented by p.
330 // The return value can be passed to Syscall to run the procedure.
331 // It will panic if the procedure cannot be found.
332 func (p *LazyProc) Addr() uintptr {
339 // Call executes procedure p with arguments a. It will panic, if more than 15 arguments
340 // are supplied. It will also panic if the procedure cannot be found.
342 // The returned error is always non-nil, constructed from the result of GetLastError.
343 // Callers must inspect the primary return value to decide whether an error occurred
344 // (according to the semantics of the specific function being called) before consulting
345 // the error. The error will be guaranteed to contain windows.Errno.
346 func (p *LazyProc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) {
348 return p.proc.Call(a...)
351 var canDoSearchSystem32Once struct {
356 func initCanDoSearchSystem32() {
357 // https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
358 // "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
359 // Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
360 // systems that have KB2533623 installed. To determine whether the
361 // flags are available, use GetProcAddress to get the address of the
362 // AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
363 // function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
364 // flags can be used with LoadLibraryEx."
365 canDoSearchSystem32Once.v = (modkernel32.NewProc("AddDllDirectory").Find() == nil)
368 func canDoSearchSystem32() bool {
369 canDoSearchSystem32Once.Do(initCanDoSearchSystem32)
370 return canDoSearchSystem32Once.v
373 func isBaseName(name string) bool {
374 for _, c := range name {
375 if c == ':' || c == '/' || c == '\\' {
382 // loadLibraryEx wraps the Windows LoadLibraryEx function.
384 // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx
386 // If name is not an absolute path, LoadLibraryEx searches for the DLL
387 // in a variety of automatic locations unless constrained by flags.
388 // See: https://msdn.microsoft.com/en-us/library/ff919712%28VS.85%29.aspx
389 func loadLibraryEx(name string, system bool) (*DLL, error) {
393 if canDoSearchSystem32() {
394 flags = LOAD_LIBRARY_SEARCH_SYSTEM32
395 } else if isBaseName(name) {
396 // WindowsXP or unpatched Windows machine
397 // trying to load "foo.dll" out of the system
398 // folder, but LoadLibraryEx doesn't support
399 // that yet on their system, so emulate it.
400 systemdir, err := GetSystemDirectory()
404 loadDLL = systemdir + "\\" + name
407 h, err := LoadLibraryEx(loadDLL, 0, flags)
411 return &DLL{Name: name, Handle: h}, nil
414 type errString string
416 func (s errString) Error() string { return string(s) }