dll_windows.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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.
  4. package windows
  5. import (
  6. "sync"
  7. "sync/atomic"
  8. "syscall"
  9. "unsafe"
  10. )
  11. // We need to use LoadLibrary and GetProcAddress from the Go runtime, because
  12. // the these symbols are loaded by the system linker and are required to
  13. // dynamically load additional symbols. Note that in the Go runtime, these
  14. // return syscall.Handle and syscall.Errno, but these are the same, in fact,
  15. // as windows.Handle and windows.Errno, and we intend to keep these the same.
  16. //go:linkname syscall_loadlibrary syscall.loadlibrary
  17. func syscall_loadlibrary(filename *uint16) (handle Handle, err Errno)
  18. //go:linkname syscall_getprocaddress syscall.getprocaddress
  19. func syscall_getprocaddress(handle Handle, procname *uint8) (proc uintptr, err Errno)
  20. // DLLError describes reasons for DLL load failures.
  21. type DLLError struct {
  22. Err error
  23. ObjName string
  24. Msg string
  25. }
  26. func (e *DLLError) Error() string { return e.Msg }
  27. func (e *DLLError) Unwrap() error { return e.Err }
  28. // A DLL implements access to a single DLL.
  29. type DLL struct {
  30. Name string
  31. Handle Handle
  32. }
  33. // LoadDLL loads DLL file into memory.
  34. //
  35. // Warning: using LoadDLL without an absolute path name is subject to
  36. // DLL preloading attacks. To safely load a system DLL, use [NewLazySystemDLL],
  37. // or use [LoadLibraryEx] directly.
  38. func LoadDLL(name string) (dll *DLL, err error) {
  39. namep, err := UTF16PtrFromString(name)
  40. if err != nil {
  41. return nil, err
  42. }
  43. h, e := syscall_loadlibrary(namep)
  44. if e != 0 {
  45. return nil, &DLLError{
  46. Err: e,
  47. ObjName: name,
  48. Msg: "Failed to load " + name + ": " + e.Error(),
  49. }
  50. }
  51. d := &DLL{
  52. Name: name,
  53. Handle: h,
  54. }
  55. return d, nil
  56. }
  57. // MustLoadDLL is like LoadDLL but panics if load operation fails.
  58. func MustLoadDLL(name string) *DLL {
  59. d, e := LoadDLL(name)
  60. if e != nil {
  61. panic(e)
  62. }
  63. return d
  64. }
  65. // FindProc searches DLL d for procedure named name and returns *Proc
  66. // if found. It returns an error if search fails.
  67. func (d *DLL) FindProc(name string) (proc *Proc, err error) {
  68. namep, err := BytePtrFromString(name)
  69. if err != nil {
  70. return nil, err
  71. }
  72. a, e := syscall_getprocaddress(d.Handle, namep)
  73. if e != 0 {
  74. return nil, &DLLError{
  75. Err: e,
  76. ObjName: name,
  77. Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(),
  78. }
  79. }
  80. p := &Proc{
  81. Dll: d,
  82. Name: name,
  83. addr: a,
  84. }
  85. return p, nil
  86. }
  87. // MustFindProc is like FindProc but panics if search fails.
  88. func (d *DLL) MustFindProc(name string) *Proc {
  89. p, e := d.FindProc(name)
  90. if e != nil {
  91. panic(e)
  92. }
  93. return p
  94. }
  95. // FindProcByOrdinal searches DLL d for procedure by ordinal and returns *Proc
  96. // if found. It returns an error if search fails.
  97. func (d *DLL) FindProcByOrdinal(ordinal uintptr) (proc *Proc, err error) {
  98. a, e := GetProcAddressByOrdinal(d.Handle, ordinal)
  99. name := "#" + itoa(int(ordinal))
  100. if e != nil {
  101. return nil, &DLLError{
  102. Err: e,
  103. ObjName: name,
  104. Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(),
  105. }
  106. }
  107. p := &Proc{
  108. Dll: d,
  109. Name: name,
  110. addr: a,
  111. }
  112. return p, nil
  113. }
  114. // MustFindProcByOrdinal is like FindProcByOrdinal but panics if search fails.
  115. func (d *DLL) MustFindProcByOrdinal(ordinal uintptr) *Proc {
  116. p, e := d.FindProcByOrdinal(ordinal)
  117. if e != nil {
  118. panic(e)
  119. }
  120. return p
  121. }
  122. // Release unloads DLL d from memory.
  123. func (d *DLL) Release() (err error) {
  124. return FreeLibrary(d.Handle)
  125. }
  126. // A Proc implements access to a procedure inside a DLL.
  127. type Proc struct {
  128. Dll *DLL
  129. Name string
  130. addr uintptr
  131. }
  132. // Addr returns the address of the procedure represented by p.
  133. // The return value can be passed to Syscall to run the procedure.
  134. func (p *Proc) Addr() uintptr {
  135. return p.addr
  136. }
  137. //go:uintptrescapes
  138. // Call executes procedure p with arguments a. It will panic, if more than 15 arguments
  139. // are supplied.
  140. //
  141. // The returned error is always non-nil, constructed from the result of GetLastError.
  142. // Callers must inspect the primary return value to decide whether an error occurred
  143. // (according to the semantics of the specific function being called) before consulting
  144. // the error. The error will be guaranteed to contain windows.Errno.
  145. func (p *Proc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) {
  146. return syscall.SyscallN(p.Addr(), a...)
  147. }
  148. // A LazyDLL implements access to a single DLL.
  149. // It will delay the load of the DLL until the first
  150. // call to its Handle method or to one of its
  151. // LazyProc's Addr method.
  152. type LazyDLL struct {
  153. Name string
  154. // System determines whether the DLL must be loaded from the
  155. // Windows System directory, bypassing the normal DLL search
  156. // path.
  157. System bool
  158. mu sync.Mutex
  159. dll *DLL // non nil once DLL is loaded
  160. }
  161. // Load loads DLL file d.Name into memory. It returns an error if fails.
  162. // Load will not try to load DLL, if it is already loaded into memory.
  163. func (d *LazyDLL) Load() error {
  164. // Non-racy version of:
  165. // if d.dll != nil {
  166. if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll))) != nil {
  167. return nil
  168. }
  169. d.mu.Lock()
  170. defer d.mu.Unlock()
  171. if d.dll != nil {
  172. return nil
  173. }
  174. // kernel32.dll is special, since it's where LoadLibraryEx comes from.
  175. // The kernel already special-cases its name, so it's always
  176. // loaded from system32.
  177. var dll *DLL
  178. var err error
  179. if d.Name == "kernel32.dll" {
  180. dll, err = LoadDLL(d.Name)
  181. } else {
  182. dll, err = loadLibraryEx(d.Name, d.System)
  183. }
  184. if err != nil {
  185. return err
  186. }
  187. // Non-racy version of:
  188. // d.dll = dll
  189. atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll)), unsafe.Pointer(dll))
  190. return nil
  191. }
  192. // mustLoad is like Load but panics if search fails.
  193. func (d *LazyDLL) mustLoad() {
  194. e := d.Load()
  195. if e != nil {
  196. panic(e)
  197. }
  198. }
  199. // Handle returns d's module handle.
  200. func (d *LazyDLL) Handle() uintptr {
  201. d.mustLoad()
  202. return uintptr(d.dll.Handle)
  203. }
  204. // NewProc returns a LazyProc for accessing the named procedure in the DLL d.
  205. func (d *LazyDLL) NewProc(name string) *LazyProc {
  206. return &LazyProc{l: d, Name: name}
  207. }
  208. // NewLazyDLL creates new LazyDLL associated with DLL file.
  209. //
  210. // Warning: using NewLazyDLL without an absolute path name is subject to
  211. // DLL preloading attacks. To safely load a system DLL, use [NewLazySystemDLL].
  212. func NewLazyDLL(name string) *LazyDLL {
  213. return &LazyDLL{Name: name}
  214. }
  215. // NewLazySystemDLL is like NewLazyDLL, but will only
  216. // search Windows System directory for the DLL if name is
  217. // a base name (like "advapi32.dll").
  218. func NewLazySystemDLL(name string) *LazyDLL {
  219. return &LazyDLL{Name: name, System: true}
  220. }
  221. // A LazyProc implements access to a procedure inside a LazyDLL.
  222. // It delays the lookup until the Addr method is called.
  223. type LazyProc struct {
  224. Name string
  225. mu sync.Mutex
  226. l *LazyDLL
  227. proc *Proc
  228. }
  229. // Find searches DLL for procedure named p.Name. It returns
  230. // an error if search fails. Find will not search procedure,
  231. // if it is already found and loaded into memory.
  232. func (p *LazyProc) Find() error {
  233. // Non-racy version of:
  234. // if p.proc == nil {
  235. if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc))) == nil {
  236. p.mu.Lock()
  237. defer p.mu.Unlock()
  238. if p.proc == nil {
  239. e := p.l.Load()
  240. if e != nil {
  241. return e
  242. }
  243. proc, e := p.l.dll.FindProc(p.Name)
  244. if e != nil {
  245. return e
  246. }
  247. // Non-racy version of:
  248. // p.proc = proc
  249. atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc)), unsafe.Pointer(proc))
  250. }
  251. }
  252. return nil
  253. }
  254. // mustFind is like Find but panics if search fails.
  255. func (p *LazyProc) mustFind() {
  256. e := p.Find()
  257. if e != nil {
  258. panic(e)
  259. }
  260. }
  261. // Addr returns the address of the procedure represented by p.
  262. // The return value can be passed to Syscall to run the procedure.
  263. // It will panic if the procedure cannot be found.
  264. func (p *LazyProc) Addr() uintptr {
  265. p.mustFind()
  266. return p.proc.Addr()
  267. }
  268. //go:uintptrescapes
  269. // Call executes procedure p with arguments a. It will panic, if more than 15 arguments
  270. // are supplied. It will also panic if the procedure cannot be found.
  271. //
  272. // The returned error is always non-nil, constructed from the result of GetLastError.
  273. // Callers must inspect the primary return value to decide whether an error occurred
  274. // (according to the semantics of the specific function being called) before consulting
  275. // the error. The error will be guaranteed to contain windows.Errno.
  276. func (p *LazyProc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) {
  277. p.mustFind()
  278. return p.proc.Call(a...)
  279. }
  280. var canDoSearchSystem32Once struct {
  281. sync.Once
  282. v bool
  283. }
  284. func initCanDoSearchSystem32() {
  285. // https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
  286. // "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
  287. // Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
  288. // systems that have KB2533623 installed. To determine whether the
  289. // flags are available, use GetProcAddress to get the address of the
  290. // AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
  291. // function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
  292. // flags can be used with LoadLibraryEx."
  293. canDoSearchSystem32Once.v = (modkernel32.NewProc("AddDllDirectory").Find() == nil)
  294. }
  295. func canDoSearchSystem32() bool {
  296. canDoSearchSystem32Once.Do(initCanDoSearchSystem32)
  297. return canDoSearchSystem32Once.v
  298. }
  299. func isBaseName(name string) bool {
  300. for _, c := range name {
  301. if c == ':' || c == '/' || c == '\\' {
  302. return false
  303. }
  304. }
  305. return true
  306. }
  307. // loadLibraryEx wraps the Windows LoadLibraryEx function.
  308. //
  309. // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx
  310. //
  311. // If name is not an absolute path, LoadLibraryEx searches for the DLL
  312. // in a variety of automatic locations unless constrained by flags.
  313. // See: https://msdn.microsoft.com/en-us/library/ff919712%28VS.85%29.aspx
  314. func loadLibraryEx(name string, system bool) (*DLL, error) {
  315. loadDLL := name
  316. var flags uintptr
  317. if system {
  318. if canDoSearchSystem32() {
  319. flags = LOAD_LIBRARY_SEARCH_SYSTEM32
  320. } else if isBaseName(name) {
  321. // WindowsXP or unpatched Windows machine
  322. // trying to load "foo.dll" out of the system
  323. // folder, but LoadLibraryEx doesn't support
  324. // that yet on their system, so emulate it.
  325. systemdir, err := GetSystemDirectory()
  326. if err != nil {
  327. return nil, err
  328. }
  329. loadDLL = systemdir + "\\" + name
  330. }
  331. }
  332. h, err := LoadLibraryEx(loadDLL, 0, flags)
  333. if err != nil {
  334. return nil, err
  335. }
  336. return &DLL{Name: name, Handle: h}, nil
  337. }