windows: add AddDllDirectory and RemoveDllDirectory

Per https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-adddlldirectory
and https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-removedlldirectory.

Change-Id: If44a3758720345d1bbd9af96ec2481fbe9398a08
Reviewed-on: https://go-review.googlesource.com/c/sys/+/537755
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
Reviewed-by: Alex Brainman <alex.brainman@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
Roland Shoemaker
2023-11-13 16:23:13 +00:00
committed by Gopher Robot
parent e4099bfacb
commit 11eadc05e9
3 changed files with 74 additions and 0 deletions
+53
View File
@@ -11,6 +11,7 @@ import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
@@ -1222,3 +1223,55 @@ func TestGetStartupInfo(t *testing.T) {
t.Fatalf("GetStartupInfo: got error %v, want nil", err)
}
}
func TestAddRemoveDllDirectory(t *testing.T) {
if _, err := exec.LookPath("gcc"); err != nil {
t.Skip("skipping test: gcc is missing")
}
dllSrc := `#include <stdint.h>
#include <windows.h>
uintptr_t beep(void) {
return 5;
}`
tmpdir := t.TempDir()
srcname := "beep.c"
err := os.WriteFile(filepath.Join(tmpdir, srcname), []byte(dllSrc), 0)
if err != nil {
t.Fatal(err)
}
name := "beep.dll"
cmd := exec.Command("gcc", "-shared", "-s", "-Werror", "-o", name, srcname)
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("failed to build dll: %v - %v", err, string(out))
}
if _, err := windows.LoadLibraryEx("beep.dll", 0, windows.LOAD_LIBRARY_SEARCH_USER_DIRS); err == nil {
t.Fatal("LoadLibraryEx unexpectedly found beep.dll")
}
dllCookie, err := windows.AddDllDirectory(windows.StringToUTF16Ptr(tmpdir))
if err != nil {
t.Fatalf("AddDllDirectory failed: %s", err)
}
handle, err := windows.LoadLibraryEx("beep.dll", 0, windows.LOAD_LIBRARY_SEARCH_USER_DIRS)
if err != nil {
t.Fatalf("LoadLibraryEx failed: %s", err)
}
if err := windows.FreeLibrary(handle); err != nil {
t.Fatalf("FreeLibrary failed: %s", err)
}
if err := windows.RemoveDllDirectory(dllCookie); err != nil {
t.Fatalf("RemoveDllDirectory failed: %s", err)
}
_, err = windows.LoadLibraryEx("beep.dll", 0, windows.LOAD_LIBRARY_SEARCH_USER_DIRS)
if err == nil {
t.Fatal("LoadLibraryEx unexpectedly found beep.dll")
}
}