Platform.cpp 12.5 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");
224
225
#else
    void *handle = dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);
Robert McGibbon's avatar
Robert McGibbon committed
226
    if (handle == NULL) {
227
        throw OpenMMException("Error loading library "+file+": "+dlerror());
Robert McGibbon's avatar
Robert McGibbon committed
228
    }
229
    return handle;
230
#endif
231
232
233
}

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

void Platform::loadPluginLibrary(const string& file) {
#ifdef WIN32
    vector<HMODULE> plugins;
#else
    vector<void*> plugins;
256
#endif
257
258
    plugins.push_back(loadOneLibrary(file));
    initializePlugins(plugins);
259
}
260

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

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

    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);
297
298
        }
    }
299

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

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

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

340
341
342
343
// Some bizarre preprocessor magic required to convert a macro to a string...
#define STRING1(x) #x
#define STRING(x) STRING1(x)

344
const string& Platform::getOpenMMVersion() {
345
#if OPENMM_BUILD_VERSION == 0
346
    static const string version = STRING(OPENMM_MAJOR_VERSION) "." STRING(OPENMM_MINOR_VERSION);
347
348
349
#else
    static const string version = STRING(OPENMM_MAJOR_VERSION) "." STRING(OPENMM_MINOR_VERSION) "." STRING(OPENMM_BUILD_VERSION);
#endif
350
351
352
    return version;
}

353
354
355
356
357
358
359
ContextImpl& Platform::getContextImpl(Context& context) const {
    return *context.impl;
}

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