dll_windows.go 11 KB

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