Platform.cpp 12.6 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
 *                                                                            *
7
 * Portions copyright (c) 2008-2026 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
113
114
115
vector<map<string, string> > Platform::getDevices(const map<string, string>& filters) const {
    return {{}};
}

116
void Platform::contextCreated(ContextImpl& context, const map<string, string>& properties) const {
117
118
}

119
120
121
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.
122

123
124
125
126
127
128
    map<string, string> properties;
    for (auto& name : getPropertyNames())
        properties[name] = getPropertyValue(originalContext.getOwner(), name);
    contextCreated(context, properties);
}

129
void Platform::contextDestroyed(ContextImpl& context) const {
130
131
}

132
void Platform::registerKernelFactory(const string& name, KernelFactory* factory) {
133
134
135
    kernelFactories[name] = factory;
}

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

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

153
void Platform::registerPlatform(Platform* platform) {
154
    getPlatforms().push_back(platform);
155
156
157
}

int Platform::getNumPlatforms() {
158
    return getPlatforms().size();
159
160
161
}

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

Peter Eastman's avatar
Peter Eastman committed
168
169
170
171
Platform& Platform::getPlatform(const string& name) {
    return getPlatformByName(name);
}

Robert McGibbon's avatar
Robert McGibbon committed
172
173
std::vector<std::string> Platform::getPluginLoadFailures() {
  return pluginLoadFailures;
Robert McGibbon's avatar
Robert McGibbon committed
174
175
}

176
Platform& Platform::getPlatformByName(const string& name) {
177
178
179
180
181
182
    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
183
Platform& Platform::findPlatform(const vector<string>& kernelNames) {
184
    Platform* best = 0;
185
    vector<Platform*>& platforms = getPlatforms();
186
    double speed = 0.0;
peastman's avatar
peastman committed
187
188
189
    for (auto platform : platforms) {
        if (platform->supportsKernels(kernelNames) && platform->getSpeed() > speed) {
            best = platform;
190
191
192
193
            speed = best->getSpeed();
        }
    }
    if (best == 0)
194
        throw OpenMMException("No Platform supports all the requested kernels");
195
196
    return *best;
}
197
198

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

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

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

void Platform::loadPluginLibrary(const string& file) {
#ifdef WIN32
    vector<HMODULE> plugins;
#else
    vector<void*> plugins;
266
#endif
267
268
    plugins.push_back(loadOneLibrary(file));
    initializePlugins(plugins);
269
}
270

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

    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);
        }
291
    }
292
    vector<HMODULE> plugins;
293
294
#else
    DIR* dir;
295
296
    dirSeparator = '/';
    pathSeparator = ':';
297
    struct dirent *entry;
298
299
300
301
302
303
304
305
306

    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);
307
308
        }
    }
309

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

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

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

350
351
352
353
// Some bizarre preprocessor magic required to convert a macro to a string...
#define STRING1(x) #x
#define STRING(x) STRING1(x)

354
const string& Platform::getOpenMMVersion() {
355
#if OPENMM_BUILD_VERSION == 0
356
    static const string version = STRING(OPENMM_MAJOR_VERSION) "." STRING(OPENMM_MINOR_VERSION);
357
358
359
#else
    static const string version = STRING(OPENMM_MAJOR_VERSION) "." STRING(OPENMM_MINOR_VERSION) "." STRING(OPENMM_BUILD_VERSION);
#endif
360
361
362
    return version;
}

363
364
365
366
367
368
369
ContextImpl& Platform::getContextImpl(Context& context) const {
    return *context.impl;
}

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