@@ -11,6 +11,7 @@ import (
11
11
"errors"
12
12
"fmt"
13
13
"os"
14
+ "os/exec"
14
15
"path/filepath"
15
16
"runtime"
16
17
"strconv"
@@ -1222,3 +1223,55 @@ func TestGetStartupInfo(t *testing.T) {
1222
1223
t .Fatalf ("GetStartupInfo: got error %v, want nil" , err )
1223
1224
}
1224
1225
}
1226
+
1227
+ func TestAddRemoveDllDirectory (t * testing.T ) {
1228
+ if _ , err := exec .LookPath ("gcc" ); err != nil {
1229
+ t .Skip ("skipping test: gcc is missing" )
1230
+ }
1231
+ dllSrc := `#include <stdint.h>
1232
+ #include <windows.h>
1233
+
1234
+ uintptr_t beep(void) {
1235
+ return 5;
1236
+ }`
1237
+ tmpdir := t .TempDir ()
1238
+ srcname := "beep.c"
1239
+ err := os .WriteFile (filepath .Join (tmpdir , srcname ), []byte (dllSrc ), 0 )
1240
+ if err != nil {
1241
+ t .Fatal (err )
1242
+ }
1243
+ name := "beep.dll"
1244
+ cmd := exec .Command ("gcc" , "-shared" , "-s" , "-Werror" , "-o" , name , srcname )
1245
+ cmd .Dir = tmpdir
1246
+ out , err := cmd .CombinedOutput ()
1247
+ if err != nil {
1248
+ t .Fatalf ("failed to build dll: %v - %v" , err , string (out ))
1249
+ }
1250
+
1251
+ if _ , err := windows .LoadLibraryEx ("beep.dll" , 0 , windows .LOAD_LIBRARY_SEARCH_USER_DIRS ); err == nil {
1252
+ t .Fatal ("LoadLibraryEx unexpectedly found beep.dll" )
1253
+ }
1254
+
1255
+ dllCookie , err := windows .AddDllDirectory (windows .StringToUTF16Ptr (tmpdir ))
1256
+ if err != nil {
1257
+ t .Fatalf ("AddDllDirectory failed: %s" , err )
1258
+ }
1259
+
1260
+ handle , err := windows .LoadLibraryEx ("beep.dll" , 0 , windows .LOAD_LIBRARY_SEARCH_USER_DIRS )
1261
+ if err != nil {
1262
+ t .Fatalf ("LoadLibraryEx failed: %s" , err )
1263
+ }
1264
+
1265
+ if err := windows .FreeLibrary (handle ); err != nil {
1266
+ t .Fatalf ("FreeLibrary failed: %s" , err )
1267
+ }
1268
+
1269
+ if err := windows .RemoveDllDirectory (dllCookie ); err != nil {
1270
+ t .Fatalf ("RemoveDllDirectory failed: %s" , err )
1271
+ }
1272
+
1273
+ _ , err = windows .LoadLibraryEx ("beep.dll" , 0 , windows .LOAD_LIBRARY_SEARCH_USER_DIRS )
1274
+ if err == nil {
1275
+ t .Fatal ("LoadLibraryEx unexpectedly found beep.dll" )
1276
+ }
1277
+ }
0 commit comments