Platform.cpp 12.6 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.               *
 *                                                                            *
9
 * Portions copyright (c) 2008-2016 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
}

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

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

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

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

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

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

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

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

    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);
301
302
        }
    }
303

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

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

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

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

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

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

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