Platform.cpp 12.5 KB
Newer Older
1
2
3
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
Evan Pretti's avatar
Evan Pretti committed
4
5
 * This is part of the OpenMM molecular simulation toolkit.                   *
 * See https://openmm.org/development.                                        *
6
 *                                                                            *
Peter Eastman's avatar
Peter Eastman committed
7
 * Portions copyright (c) 2008-2024 Stanford University and the Authors.      *
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 * Authors: Peter Eastman                                                     *
 * Contributors:                                                              *
 *                                                                            *
 * Permission is hereby granted, free of charge, to any person obtaining a    *
 * copy of this software and associated documentation files (the "Software"), *
 * to deal in the Software without restriction, including without limitation  *
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,   *
 * and/or sell copies of the Software, and to permit persons to whom the      *
 * Software is furnished to do so, subject to the following conditions:       *
 *                                                                            *
 * The above copyright notice and this permission notice shall be included in *
 * all copies or substantial portions of the Software.                        *
 *                                                                            *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    *
 * THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,    *
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR      *
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE  *
 * USE OR OTHER DEALINGS IN THE SOFTWARE.                                     *
 * -------------------------------------------------------------------------- */

30
#include "openmm/Platform.h"
31
#include "openmm/Context.h"
32
33
34
#include "openmm/OpenMMException.h"
#include "openmm/Kernel.h"
#include "openmm/KernelFactory.h"
35
#include "openmm/internal/ContextImpl.h"
36
37
38
#ifdef WIN32
#include <windows.h>
#else
39
40
41
#ifndef __PNACL__
    #include <dlfcn.h>
#endif
42
#include <dirent.h>
43
#include <cstdlib>
44
#endif
45
#include <sstream>
46
#include <set>
47
#include <algorithm>
48

49
50
#include "ReferencePlatform.h"

51
52
53
using namespace OpenMM;
using namespace std;

Robert McGibbon's avatar
Robert McGibbon committed
54
std::vector<std::string> Platform::pluginLoadFailures;
55
56
57
static bool stringLengthComparator(string i, string j) {
  return (i.size() < j.size());
}
Robert McGibbon's avatar
Robert McGibbon committed
58

59
60
61
static int registerPlatforms() {

    // Register the Platforms built into the main library.  This should eventually be moved elsewhere.
62

63
64
65
66
67
68
69
    ReferencePlatform* platform = new ReferencePlatform();
    Platform::registerPlatform(platform);
    return 0;
}

static int platformInitializer = registerPlatforms();

70
71
Platform::~Platform() {
    set<KernelFactory*> uniqueKernelFactories;
peastman's avatar
peastman committed
72
73
74
75
    for (auto& factory : kernelFactories)
        uniqueKernelFactories.insert(factory.second);
    for (auto factory : uniqueKernelFactories)
        delete factory;
76
77
}

Peter Eastman's avatar
Peter Eastman committed
78
const vector<string>& Platform::getPropertyNames() const {
79
80
81
82
83
84
85
86
87
88
89
90
    return platformProperties;
}

const string& Platform::getPropertyValue(const Context& context, const string& property) const {
    throw OpenMMException("getPropertyValue: Illegal property name");
}

void Platform::setPropertyValue(Context& context, const string& property, const string& value) const {
    throw OpenMMException("setPropertyValue: Illegal property name");
}

const string& Platform::getPropertyDefaultValue(const string& property) const {
91
92
93
94
    string propertyName = property;
    if (deprecatedPropertyReplacements.find(property) != deprecatedPropertyReplacements.end())
        propertyName = deprecatedPropertyReplacements.find(property)->second;
    map<string, string>::const_iterator value = defaultProperties.find(propertyName);
95
96
97
98
99
100
    if (value == defaultProperties.end())
        throw OpenMMException("getPropertyDefaultValue: Illegal property name");
    return value->second;
}

void Platform::setPropertyDefaultValue(const string& property, const string& value) {
101
102
103
    string propertyName = property;
    if (deprecatedPropertyReplacements.find(property) != deprecatedPropertyReplacements.end())
        propertyName = deprecatedPropertyReplacements.find(property)->second;
peastman's avatar
peastman committed
104
105
    for (auto& prop : platformProperties)
        if (prop == propertyName) {
106
            defaultProperties[propertyName] = value;
107
108
109
            return;
        }
    throw OpenMMException("setPropertyDefaultValue: Illegal property name");
110
111
}

112
void Platform::contextCreated(ContextImpl& context, const map<string, string>& properties) const {
113
114
}

115
116
117
void Platform::linkedContextCreated(ContextImpl& context, ContextImpl& originalContext) const {
    // The default implementation just copies over the properties and calls contextCreated().
    // Subclasses may override this to do something different.
118

119
120
121
122
123
124
    map<string, string> properties;
    for (auto& name : getPropertyNames())
        properties[name] = getPropertyValue(originalContext.getOwner(), name);
    contextCreated(context, properties);
}

125
void Platform::contextDestroyed(ContextImpl& context) const {
126
127
}

128
void Platform::registerKernelFactory(const string& name, KernelFactory* factory) {
129
130
131
    kernelFactories[name] = factory;
}

Peter Eastman's avatar
Peter Eastman committed
132
bool Platform::supportsKernels(const vector<string>& kernelNames) const {
peastman's avatar
peastman committed
133
134
    for (auto& name : kernelNames)
        if (kernelFactories.find(name) == kernelFactories.end())
135
136
137
138
            return false;
    return true;
}

139
Kernel Platform::createKernel(const string& name, ContextImpl& context) const {
140
    if (kernelFactories.find(name) == kernelFactories.end())
141
        throw OpenMMException("Called createKernel() on a Platform which does not support the requested kernel");
142
    return Kernel(kernelFactories.find(name)->second->createKernelImpl(name, *this, context));
143
}
144
145
146
147
148
vector<Platform*>& Platform::getPlatforms() {
    static vector<Platform*> platforms;
    return platforms;
}

149
void Platform::registerPlatform(Platform* platform) {
150
    getPlatforms().push_back(platform);
151
152
153
}

int Platform::getNumPlatforms() {
154
    return getPlatforms().size();
155
156
157
}

Platform& Platform::getPlatform(int index) {
Robert McGibbon's avatar
Robert McGibbon committed
158
159
160
161
    if (index >= 0 && index < getNumPlatforms()) {
        return *getPlatforms()[index];
    }
    throw OpenMMException("Invalid platform index");
162
163
}

Peter Eastman's avatar
Peter Eastman committed
164
165
166
167
Platform& Platform::getPlatform(const string& name) {
    return getPlatformByName(name);
}

Robert McGibbon's avatar
Robert McGibbon committed
168
169
std::vector<std::string> Platform::getPluginLoadFailures() {
  return pluginLoadFailures;
Robert McGibbon's avatar
Robert McGibbon committed
170
171
}

172
Platform& Platform::getPlatformByName(const string& name) {
173
174
175
176
177
178
    for (int i = 0; i < getNumPlatforms(); i++)
        if (getPlatform(i).getName() == name)
            return getPlatform(i);
    throw OpenMMException("There is no registered Platform called \""+name+"\"");
}

Peter Eastman's avatar
Peter Eastman committed
179
Platform& Platform::findPlatform(const vector<string>& kernelNames) {
180
    Platform* best = 0;
181
    vector<Platform*>& platforms = getPlatforms();
182
    double speed = 0.0;
peastman's avatar
peastman committed
183
184
185
    for (auto platform : platforms) {
        if (platform->supportsKernels(kernelNames) && platform->getSpeed() > speed) {
            best = platform;
186
187
188
189
            speed = best->getSpeed();
        }
    }
    if (best == 0)
190
        throw OpenMMException("No Platform supports all the requested kernels");
191
192
    return *best;
}
193
194

#ifdef WIN32
195
static HMODULE loadOneLibrary(const string& file) {
196
197
    // Tell Windows not to bother the user with ugly error boxes.
    const UINT oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
198
    HMODULE handle = LoadLibrary(file.c_str());
199
    SetErrorMode(oldErrorMode); // Restore previous error mode.
200
    if (handle == NULL) {
201
202
203
        stringstream message;
        message << "Error loading library " << file << ": " << GetLastError();
        throw OpenMMException(message.str());
204
    }
205
206
207
208
    return handle;
}

static void initializePlugins(vector<HMODULE>& plugins) {
peastman's avatar
peastman committed
209
    for (auto plugin : plugins) {
210
        void (*init)();
peastman's avatar
peastman committed
211
        *(void **)(&init) = (void *) GetProcAddress(plugin, "registerPlatforms");
212
213
214
        if (init != NULL)
            (*init)();
    }
peastman's avatar
peastman committed
215
    for (auto plugin : plugins) {
216
        void (*init)();
peastman's avatar
peastman committed
217
        *(void **)(&init) = (void *) GetProcAddress(plugin, "registerKernelFactories");
218
219
220
221
        if (init != NULL)
            (*init)();
    }
}
222
#else
223
static void* loadOneLibrary(const string& file) {
224
225
#ifdef __PNACL__
    throw OpenMMException("Loading dynamic libraries is not supported on PNaCl");
peastman's avatar
peastman committed
226
227
228
#else
#ifdef __APPLE__
    void *handle = dlopen(file.c_str(), RTLD_LAZY | RTLD_GLOBAL);
229
230
#else
    void *handle = dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);
peastman's avatar
peastman committed
231
#endif
Robert McGibbon's avatar
Robert McGibbon committed
232
    if (handle == NULL) {
233
        throw OpenMMException("Error loading library "+file+": "+dlerror());
Robert McGibbon's avatar
Robert McGibbon committed
234
    }
235
    return handle;
236
#endif
237
238
239
}

static void initializePlugins(vector<void*>& plugins) {
240
#ifndef __PNACL__
peastman's avatar
peastman committed
241
    for (auto plugin : plugins) {
242
        void (*init)();
peastman's avatar
peastman committed
243
        *(void **)(&init) = dlsym(plugin, "registerPlatforms");
244
245
246
        if (init != NULL)
            (*init)();
    }
peastman's avatar
peastman committed
247
    for (auto plugin : plugins) {
248
        void (*init)();
peastman's avatar
peastman committed
249
        *(void **)(&init) = dlsym(plugin, "registerKernelFactories");
250
251
252
        if (init != NULL)
            (*init)();
    }
253
#endif
254
255
256
257
258
259
260
261
}
#endif

void Platform::loadPluginLibrary(const string& file) {
#ifdef WIN32
    vector<HMODULE> plugins;
#else
    vector<void*> plugins;
262
#endif
263
264
    plugins.push_back(loadOneLibrary(file));
    initializePlugins(plugins);
265
}
266

267
vector<string> Platform::loadPluginsFromDirectory(const string& directory) {
268
269
    vector<string> files;
    char dirSeparator;
270
271
    char pathSeparator;
    stringstream sdirectory(directory);
272
#ifdef WIN32
273
    dirSeparator = '\\';
274
    pathSeparator = ';';
275
    WIN32_FIND_DATA fileInfo;
276
277
278
279
280
281
282
283
284
285
286

    for (string path; std::getline(sdirectory, path, pathSeparator);) {
        string filePattern(path + dirSeparator + "*.dll");
        HANDLE findHandle = FindFirstFile(filePattern.c_str(), &fileInfo);
        if (findHandle != INVALID_HANDLE_VALUE) {
            do {
                if (fileInfo.cFileName[0] != '.')
                    files.push_back(path+dirSeparator+string(fileInfo.cFileName));
            } while (FindNextFile(findHandle, &fileInfo));
            FindClose(findHandle);
        }
287
    }
288
    vector<HMODULE> plugins;
289
290
#else
    DIR* dir;
291
292
    dirSeparator = '/';
    pathSeparator = ':';
293
    struct dirent *entry;
294
295
296
297
298
299
300
301
302

    for (string path; std::getline(sdirectory, path, pathSeparator);) {
        dir = opendir(path.c_str());
        if (dir != NULL) {
            while ((entry = readdir(dir)) != NULL) {
                if (entry->d_name[0] != '.')
                    files.push_back(path+dirSeparator+string(entry->d_name));
            }
            closedir(dir);
303
304
        }
    }
305

306
    vector<void*> plugins;
307
308
#endif
    vector<string> loadedLibraries;
Robert McGibbon's avatar
Robert McGibbon committed
309
    pluginLoadFailures.resize(0);
310
    std::sort (files.begin(), files.end(), stringLengthComparator);
Robert McGibbon's avatar
Robert McGibbon committed
311

312
313
    for (unsigned int i = 0; i < files.size(); ++i) {
        try {
314
            plugins.push_back(loadOneLibrary(files[i]));
315
            loadedLibraries.push_back(files[i]);
316
        } catch (OpenMMException& ex) {
Robert McGibbon's avatar
Robert McGibbon committed
317
	    pluginLoadFailures.push_back(ex.what());
318
319
        }
    }
320
    initializePlugins(plugins);
321
322
    return loadedLibraries;
}
323

Peter Eastman's avatar
Peter Eastman committed
324
const string& Platform::getDefaultPluginsDirectory() {
325
    char* dir = getenv("OPENMM_PLUGIN_DIR");
326
    static string directory;
327
#ifdef _MSC_VER
328
    if (dir != NULL)
329
330
331
332
333
334
335
336
        directory = string(dir);
    else {
        dir = getenv("PROGRAMFILES");
        if (dir == NULL)
            directory = "C:\\\\Program Files\\OpenMM\\lib\\plugins";
        else
            directory = string(dir)+"\\OpenMM\\lib\\plugins";
    }
337
338
#else
    if (dir == NULL)
Peter Eastman's avatar
Peter Eastman committed
339
340
341
        directory = "/usr/local/openmm/lib/plugins";
    else
        directory = string(dir);
342
#endif
343
    return directory;
344
}
345

346
347
348
349
// Some bizarre preprocessor magic required to convert a macro to a string...
#define STRING1(x) #x
#define STRING(x) STRING1(x)

350
const string& Platform::getOpenMMVersion() {
351
#if OPENMM_BUILD_VERSION == 0
352
    static const string version = STRING(OPENMM_MAJOR_VERSION) "." STRING(OPENMM_MINOR_VERSION);
353
354
355
#else
    static const string version = STRING(OPENMM_MAJOR_VERSION) "." STRING(OPENMM_MINOR_VERSION) "." STRING(OPENMM_BUILD_VERSION);
#endif
356
357
358
    return version;
}

359
360
361
362
363
364
365
ContextImpl& Platform::getContextImpl(Context& context) const {
    return *context.impl;
}

const ContextImpl& Platform::getContextImpl(const Context& context) const {
    return *context.impl;
}