IVGCVSW-3595 Implement the LoadDynamicBackends function in the Runtime class
[platform/upstream/armnn.git] / src / backends / backendsCommon / DynamicBackendUtils.hpp
1 //
2 // Copyright © 2017 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5
6 #pragma once
7
8 #include "IBackendInternal.hpp"
9 #include "DynamicBackend.hpp"
10
11 #include <armnn/Exceptions.hpp>
12
13 #include <string>
14 #include <dlfcn.h>
15 #include <vector>
16
17 #include <boost/format.hpp>
18
19 #if !defined(DYNAMIC_BACKEND_PATHS)
20 #define DYNAMIC_BACKEND_PATHS ""
21 #endif
22
23 namespace armnn
24 {
25
26 class DynamicBackendUtils
27 {
28 public:
29     static void* OpenHandle(const std::string& sharedObjectPath);
30     static void CloseHandle(const void* sharedObjectHandle);
31
32     template<typename EntryPointType>
33     static EntryPointType GetEntryPoint(const void* sharedObjectHandle, const char* symbolName);
34
35     static bool IsBackendCompatible(const BackendVersion& backendVersion);
36
37     static std::vector<std::string> GetBackendPaths(const std::string& overrideBackendPath = "");
38     static bool IsPathValid(const std::string& path);
39     static std::vector<std::string> GetSharedObjects(const std::vector<std::string>& backendPaths);
40
41     static std::vector<DynamicBackendPtr> CreateDynamicBackends(const std::vector<std::string>& sharedObjects);
42
43 protected:
44     /// Protected methods for testing purposes
45     static bool IsBackendCompatibleImpl(const BackendVersion& backendApiVersion, const BackendVersion& backendVersion);
46     static std::vector<std::string> GetBackendPathsImpl(const std::string& backendPaths);
47
48 private:
49     static std::string GetDlError();
50
51     /// This class is to hold utility functions only
52     DynamicBackendUtils() = delete;
53 };
54
55 template<typename EntryPointType>
56 EntryPointType DynamicBackendUtils::GetEntryPoint(const void* sharedObjectHandle, const char* symbolName)
57 {
58     if (sharedObjectHandle == nullptr)
59     {
60         throw RuntimeException("GetEntryPoint error: invalid handle");
61     }
62
63     if (symbolName == nullptr)
64     {
65         throw RuntimeException("GetEntryPoint error: invalid symbol");
66     }
67
68     auto entryPoint = reinterpret_cast<EntryPointType>(dlsym(const_cast<void*>(sharedObjectHandle), symbolName));
69     if (!entryPoint)
70     {
71         throw RuntimeException(boost::str(boost::format("GetEntryPoint error: %1%") % GetDlError()));
72     }
73
74     return entryPoint;
75 }
76
77 } // namespace armnn