Platform.cpp 12.7 KB
Newer Older
1
2
3
4
5
6
7
8
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
 * This is part of the OpenMM molecular simulation toolkit originating from   *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org.               *
 *                                                                            *
Peter Eastman's avatar
Peter Eastman committed
9
 * Portions copyright (c) 2008-2024 Stanford University and the Authors.      *
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 * 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.                                     *
 * -------------------------------------------------------------------------- */

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

51
52
#include "ReferencePlatform.h"

53
54
55
using namespace OpenMM;
using namespace std;

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

61
62
63
static int registerPlatforms() {

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

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

static int platformInitializer = registerPlatforms();

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

Peter Eastman's avatar
Peter Eastman committed
80
const vector<string>& Platform::getPropertyNames() const {
81
82
83
84
85
86
87
88
89
90
91
92
    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 {
93
94
95
96
    string propertyName = property;
    if (deprecatedPropertyReplacements.find(property) != deprecatedPropertyReplacements.end())
        propertyName = deprecatedPropertyReplacements.find(property)->second;
    map<string, string>::const_iterator value = defaultProperties.find(propertyName);
97
98
99
100
101
102
    if (value == defaultProperties.end())
        throw OpenMMException("getPropertyDefaultValue: Illegal property name");
    return value->second;
}

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

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

117
118
119
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.
120

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

127
void Platform::contextDestroyed(ContextImpl& context) const {
128
129
}

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

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

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

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

int Platform::getNumPlatforms() {
156
    return getPlatforms().size();
157
158
159
}

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

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

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

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

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

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

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

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

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

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

    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);
305
306
        }
    }
307

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

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

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

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

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

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

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