2727#include " llvm/Support/raw_ostream.h"
2828#include " llvm/Support/YAMLParser.h"
2929#include < mutex>
30+
31+ #if defined(_WIN32) && !defined(__CYGWIN__)
32+ #define NOMINMAX
33+ #include < Windows.h>
34+ #else
3035#include < dlfcn.h>
36+ #endif
3137
3238using namespace SourceKit ;
3339using namespace sourcekitd ;
@@ -271,6 +277,31 @@ bool sourcekitd::shutdownClient() {
271277
272278extern " C" const char __dso_handle[];
273279
280+ static void withCurrentLibraryPath (llvm::function_ref<void (const char *)> body) {
281+ #if defined(_WIN32) && !defined(__CYGWIN__)
282+ char path[MAX_PATH];
283+ HMODULE currentModule = NULL ;
284+
285+ if (GetModuleHandleExW (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
286+ GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
287+ (LPCWSTR) &withCurrentLibraryPath, ¤tModule) == 0 ) {
288+ int error = GetLastError ();
289+ LOG_WARN (" plugin-loading" , " failed to determine current Windows module. Error: " << error);
290+ return body (nullptr );
291+ }
292+ if (GetModuleFileNameA (currentModule, path, sizeof (path)) == 0 ) {
293+ int error = GetLastError ();
294+ LOG_WARN (" plugin-loading" , " failed to path of current Windows module. Error: " << error);
295+ return body (nullptr );
296+ }
297+ return body (path);
298+ #else
299+ Dl_info dlinfo;
300+ dladdr (__dso_handle, &dlinfo);
301+ return body (dlinfo.dli_fname );
302+ #endif
303+ }
304+
274305static void loadPlugin (StringRef plugin, PluginInitParams &pluginParams) {
275306 std::string err;
276307 auto *handle = swift::loadLibrary (plugin.str ().c_str (), &err);
@@ -283,9 +314,9 @@ static void loadPlugin(StringRef plugin, PluginInitParams &pluginParams) {
283314 auto *plugin_init_2 = (sourcekitd_plugin_initialize_2_t )swift::getAddressOfSymbol (
284315 handle, " sourcekitd_plugin_initialize_2" );
285316 if (plugin_init_2) {
286- Dl_info dlinfo;
287- dladdr (__dso_handle, &dlinfo );
288- plugin_init_2 (&pluginParams, dlinfo. dli_fname );
317+ withCurrentLibraryPath ([&]( const char *currentLibraryPath) {
318+ plugin_init_2 (&pluginParams, currentLibraryPath );
319+ } );
289320 return ;
290321 }
291322
0 commit comments