summaryrefslogtreecommitdiff
path: root/src/CommonAPI/Runtime.cpp
blob: 812b410e6f9ce9a4ebe9dff0a99018fe00becb78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/* Copyright (C) 2013 BMW Group
 * Author: Manfred Bathelt (manfred.bathelt@bmw.de)
 * Author: Juergen Gehring (juergen.gehring@bmw.de)
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <sys/types.h>
#include <sys/stat.h>
#ifndef WIN32
#include <dirent.h>
#include <dlfcn.h>
#endif

#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <stdexcept>

#include "Runtime.h"
#include "Configuration.h"
#include "utils.h"


namespace CommonAPI {


static std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>* registeredRuntimeLoadFunctions_;
static bool isDynamic_ = false;

static const char COMMONAPI_LIB_PREFIX[] = "libCommonAPI-";
static const char MIDDLEWARE_INFO_SYMBOL_NAME[] = "middlewareInfo";

#ifndef WIN32
inline bool Runtime::tryLoadLibrary(const std::string& libraryPath,
                                    void** sharedLibraryHandle,
                                    MiddlewareInfo** foundMiddlewareInfo) {

    //In case we find an already loaded library again while looking for another one,
    //there is no need to look at it
    if (dlopen(libraryPath.c_str(), RTLD_NOLOAD)) {
        return false;
    }

    //In order to place symbols of the newly loaded library ahead of already resolved symbols, we need
    //RTLD_DEEPBIND. This is necessary for this case: A library already is linked at compile time, but while
    //trying to resolve another library dynamically we might find the very same library again.
    //dlopen() doesn't know about the compile time linked library and will close it if dlclose() ever is
    //called, thereby causing memory corruptions. Therefore, we must be able to access the middlewareInfo
    //of the newly dlopened library in order to determine whether it already has been linked.
    *sharedLibraryHandle = dlopen(libraryPath.c_str(), RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
    if (sharedLibraryHandle == NULL) {
        return false;
    }

    *foundMiddlewareInfo = static_cast<MiddlewareInfo*>(dlsym(*sharedLibraryHandle, MIDDLEWARE_INFO_SYMBOL_NAME));

    //In this context, a resolved value of NULL it is just as invalid as if dlerror() was set additionally.
    if (!*foundMiddlewareInfo) {
        dlclose(*sharedLibraryHandle);
        return false;
    }

    if (!(*foundMiddlewareInfo)->middlewareName_ || !(*foundMiddlewareInfo)->getInstance_) {
        dlclose(sharedLibraryHandle);
        return false;
    }

    return true;
}

bool Runtime::checkAndLoadLibrary(const std::string& libraryPath,
                                  const std::string& requestedBindingIdentifier,
                                  bool keepLibrary) {

    void* sharedLibraryHandle = NULL;
    MiddlewareInfo* foundMiddlewareInfo;
    if (!tryLoadLibrary(libraryPath, &sharedLibraryHandle, &foundMiddlewareInfo)) {
        return false;
    }

    if (foundMiddlewareInfo->middlewareName_ != requestedBindingIdentifier) {
        //If library was linked at compile time (and therefore an appropriate runtime loader is registered),
        //the library must not be closed!
        auto foundRegisteredRuntimeLoader = registeredRuntimeLoadFunctions_->find(foundMiddlewareInfo->middlewareName_);
        if (foundRegisteredRuntimeLoader == registeredRuntimeLoadFunctions_->end()) {
            dlclose(sharedLibraryHandle);
        }
        return false;
    }

    if (!keepLibrary) {
        dlclose(sharedLibraryHandle);
    } else {
        //Extend visibility to make symbols available to all other libraries that are loaded afterwards,
        //e.g. libraries containing generated binding specific code.
        sharedLibraryHandle = dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_GLOBAL);
        if (!sharedLibraryHandle) {
            return false;
        }
        registeredRuntimeLoadFunctions_->insert( {foundMiddlewareInfo->middlewareName_, foundMiddlewareInfo->getInstance_} );
    }

    return true;
}

bool Runtime::checkAndLoadDefaultLibrary(std::string& foundBindingIdentifier, const std::string& libraryPath) {
    void* sharedLibraryHandle = NULL;
    MiddlewareInfo* foundMiddlewareInfo;
    if (!tryLoadLibrary(libraryPath, &sharedLibraryHandle, &foundMiddlewareInfo)) {
        return false;
    }

    //Extend visibility to make symbols available to all other linked libraries,
    //e.g. libraries containing generated binding specific code
    sharedLibraryHandle = dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_GLOBAL);
    if (!sharedLibraryHandle) {
        return false;
    }
    registeredRuntimeLoadFunctions_->insert( {foundMiddlewareInfo->middlewareName_, foundMiddlewareInfo->getInstance_} );
    foundBindingIdentifier = foundMiddlewareInfo->middlewareName_;

    return true;
}

const std::vector<std::string> Runtime::readDirectory(const std::string& path) {
    std::vector<std::string> result;
    struct stat filestat;

    DIR *directory = opendir(path.c_str());

    if (!directory) {
        return std::vector<std::string>();
    }

    struct dirent* entry;

    while ((entry = readdir(directory))) {
        const std::string fqnOfEntry = path + entry->d_name;

        if (stat(fqnOfEntry.c_str(), &filestat)) {
            continue;
        }
        if (S_ISDIR(filestat.st_mode)) {
            continue;
        }

        if (strncmp(COMMONAPI_LIB_PREFIX, entry->d_name, strlen(COMMONAPI_LIB_PREFIX)) != 0) {
            continue;
        }

        const char* fileNamePtr = entry->d_name;
        while ((fileNamePtr = strchr(fileNamePtr + 1, '.'))) {
            if (strncmp(".so", fileNamePtr, 3) == 0) {
                break;
            }
        }

        if (fileNamePtr) {
            result.push_back(fqnOfEntry);
        }
    }

    closedir (directory);

    std::sort( result.begin(), result.end() );

    return result;
}
#endif

struct LibraryVersion {
    int32_t major;
    int32_t minor;
    int32_t revision;
};

bool operator<(LibraryVersion const& lhs, LibraryVersion const& rhs) {
    if (lhs.major == rhs.major) {
        if (lhs.minor == rhs.minor) {
            return lhs.revision < rhs.revision;
        }
        return lhs.minor < rhs.minor;
    }
    return lhs.major < rhs.major;
}

#ifndef WIN32
std::shared_ptr<Runtime> Runtime::checkDynamicLibraries(const std::string& requestedMiddlewareName, LoadState& loadState) {
    const std::string& middlewareLibraryPath = Configuration::getInstance().getMiddlewareLibraryPath(requestedMiddlewareName);

    if (middlewareLibraryPath != "") {
        if (!checkAndLoadLibrary(middlewareLibraryPath, requestedMiddlewareName, true)) {
            //A path for requestedMiddlewareName was configured, but no corresponding library was found
            loadState = LoadState::CONFIGURATION_ERROR;
            return std::shared_ptr<Runtime>(NULL);
        } else {
            const std::string currentBinaryFQN = getCurrentBinaryFileFQN();
            const uint32_t lastPathSeparatorPosition = currentBinaryFQN.find_last_of("/\\");
            const std::string currentBinaryPath = currentBinaryFQN.substr(0, lastPathSeparatorPosition + 1);
            auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(requestedMiddlewareName);
            if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) {
                return (foundRuntimeLoader->second)();
            }
            //One should not get here
            loadState = LoadState::BINDING_ERROR;
            return std::shared_ptr<Runtime>(NULL);
        }
    }

    const std::vector<std::string>& librarySearchPaths = Configuration::getInstance().getLibrarySearchPaths();

    LibraryVersion highestVersionFound = {0, 0, 0};
    std::string fqnOfHighestVersion = "";
    struct stat filestat;

    for (const std::string& singleSearchPath: librarySearchPaths) {
        std::vector<std::string> orderedLibraries = readDirectory(singleSearchPath);

        for (const std::string& fqnOfEntry : orderedLibraries) {
            std::string versionString;
            LibraryVersion currentLibraryVersion = {-1, -1, -1};

            const char* fileNamePtr = fqnOfEntry.c_str();
            while ((fileNamePtr = strchr(fileNamePtr + 1, '.'))) {
                if (strncmp(".so", fileNamePtr, 3) == 0) {
                    break;
                }
            }

            const char* positionOfFirstDot = strchr(fileNamePtr + 1, '.');
            if (positionOfFirstDot) {
                versionString = positionOfFirstDot + 1;
            }

            std::vector<std::string> versionElements = split(versionString, '.');
            if (versionElements.size() >= 1 && containsOnlyDigits(versionElements[0])) {
                currentLibraryVersion.major = strtol(versionElements[0].c_str(), NULL, 0);
            }
            if (versionElements.size() >= 3 && containsOnlyDigits(versionElements[2])) {
                currentLibraryVersion.minor = strtol(versionElements[1].c_str(), NULL, 0);
                currentLibraryVersion.revision = strtol(versionElements[2].c_str(), NULL, 0);
            }

            if (highestVersionFound < currentLibraryVersion) {
                if (!checkAndLoadLibrary(fqnOfEntry, requestedMiddlewareName, false)) {
                    continue;
                }
                highestVersionFound = currentLibraryVersion;
                fqnOfHighestVersion = fqnOfEntry;
            }
        }
    }

    if (fqnOfHighestVersion != "") {
        checkAndLoadLibrary(fqnOfHighestVersion, requestedMiddlewareName, true);

        auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(requestedMiddlewareName);
        if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) {
            std::shared_ptr<Runtime> loadedRuntime = foundRuntimeLoader->second();
            if (!loadedRuntime) {
                loadState = LoadState::BINDING_ERROR;
            }
            return loadedRuntime;
        }
    }

    loadState = LoadState::NO_LIBRARY_FOUND;

    return std::shared_ptr<Runtime>();
}


std::shared_ptr<Runtime> Runtime::checkDynamicLibraries(LoadState& loadState) {
    const std::vector<std::string>& librarySearchPaths = Configuration::getInstance().getLibrarySearchPaths();

    for (const std::string& singleSearchPath : librarySearchPaths) {
        std::vector<std::string> orderedLibraries = readDirectory(singleSearchPath);

        for (const std::string& fqnOfEntry: orderedLibraries) {
            std::string foundBindingName;
            if (!checkAndLoadDefaultLibrary(foundBindingName, fqnOfEntry)) {
                continue;
            }

            auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(foundBindingName);
            if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) {
                return (foundRuntimeLoader->second)();
            }
        }
    }

    loadState = LoadState::NO_LIBRARY_FOUND;

    return std::shared_ptr<Runtime>();
}
#endif

void Runtime::registerRuntimeLoader(const std::string& middlewareName, const MiddlewareRuntimeLoadFunction& middlewareRuntimeLoadFunction) {
    if (!registeredRuntimeLoadFunctions_) {
        registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>();
    }
    if (!isDynamic_) {
        registeredRuntimeLoadFunctions_->insert( {middlewareName, middlewareRuntimeLoadFunction});
    }
}


std::shared_ptr<Runtime> Runtime::load() {
    LoadState dummyState;
    return load(dummyState);
}


std::shared_ptr<Runtime> Runtime::load(LoadState& loadState) {
    isDynamic_ = true;
    loadState = LoadState::SUCCESS;
    if(!registeredRuntimeLoadFunctions_) {
        registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>();
    }

    const std::string& defaultBindingIdentifier = Configuration::getInstance().getDefaultMiddlewareIdentifier();
    if (defaultBindingIdentifier != "") {
        const auto defaultRuntimeLoader = registeredRuntimeLoadFunctions_->find(defaultBindingIdentifier);
        if (defaultRuntimeLoader != registeredRuntimeLoadFunctions_->end()) {
            return (defaultRuntimeLoader->second)();
        }

#ifdef WIN32
        return std::shared_ptr<Runtime>();
#else
        return checkDynamicLibraries(defaultBindingIdentifier, loadState);
#endif

    } else {
        const auto defaultRuntimeLoader = registeredRuntimeLoadFunctions_->begin();
        if (defaultRuntimeLoader != registeredRuntimeLoadFunctions_->end()) {
            return (defaultRuntimeLoader->second)();
        }
#ifdef WIN32
        return std::shared_ptr<Runtime>();
#else
        return checkDynamicLibraries(loadState);
#endif
    }
}


std::shared_ptr<Runtime> Runtime::load(const std::string& middlewareIdOrAlias) {
    LoadState dummyState;
    return load(middlewareIdOrAlias, dummyState);
}

std::shared_ptr<Runtime> Runtime::load(const std::string& middlewareIdOrAlias, LoadState& loadState) {
    isDynamic_ = true;
    loadState = LoadState::SUCCESS;
    if (!registeredRuntimeLoadFunctions_) {
        registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>();
    }

    const std::string middlewareName = Configuration::getInstance().getMiddlewareNameForAlias(middlewareIdOrAlias);

    auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(middlewareName);
    if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) {
        return (foundRuntimeLoader->second)();
    }

#ifdef WIN32
    return std::shared_ptr<Runtime>();
#else
    return checkDynamicLibraries(middlewareName, loadState);
#endif
}


std::shared_ptr<MainLoopContext> Runtime::getNewMainLoopContext() const {
    return std::make_shared<MainLoopContext>();
}

std::shared_ptr<Factory> Runtime::createFactory(const std::string factoryName,
                                                const bool nullOnInvalidName) {
    return createFactory(std::shared_ptr<MainLoopContext>(NULL), factoryName, nullOnInvalidName);
}

std::shared_ptr<Factory> Runtime::createFactory(std::shared_ptr<MainLoopContext> mainLoopContext,
                                                const std::string factoryName,
                                                const bool nullOnInvalidName) {
    if(mainLoopContext && !mainLoopContext->isInitialized()) {
        return std::shared_ptr<Factory>(NULL);
    }
    return doCreateFactory(mainLoopContext, factoryName, nullOnInvalidName);
}


} // namespace CommonAPI