summaryrefslogtreecommitdiffstats
path: root/xbmc/addons/kodi-addon-dev-kit/include/kodi/tools/DllHelper.h
blob: 3cc9eea239f1ba949ee35ba1219a2a38a43a9865 (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
/*
 *  Copyright (C) 2005-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#pragma once

#ifdef __cplusplus

#include <string>

#include <dlfcn.h>
#include <kodi/AddonBase.h>
#include <kodi/Filesystem.h>

//==============================================================================
/// @ingroup cpp_kodi_tools_CDllHelper
/// @brief Macro to translate the given pointer value name of functions to
/// requested function name.
///
/// @note This should always be used and does the work of
/// @ref kodi::tools::CDllHelper::RegisterSymbol().
///
#define REGISTER_DLL_SYMBOL(functionPtr) \
  kodi::tools::CDllHelper::RegisterSymbol(functionPtr, #functionPtr)
//------------------------------------------------------------------------------

namespace kodi
{
namespace tools
{

//==============================================================================
/// @defgroup cpp_kodi_tools_CDllHelper class CDllHelper
/// @ingroup cpp_kodi_tools
/// @brief **Class to help with load of shared library functions**\n
/// You can add them as parent to your class and to help with load of shared
/// library functions.
///
/// @note To use on Windows must you also include [dlfcn-win32](https://github.com/dlfcn-win32/dlfcn-win32)
/// on your addon!\n\n
/// Furthermore, this allows the use of Android where the required library is
/// copied to an EXE useable folder.
///
///
/// ----------------------------------------------------------------------------
///
/// **Example:**
/// ~~~~~~~~~~~~~{.cpp}
///
/// #include <kodi/tools/DllHelper.h>
///
/// ...
/// class CMyInstance : public kodi::addon::CInstanceAudioDecoder,
///                     private kodi::tools::CDllHelper
/// {
/// public:
///   CMyInstance(KODI_HANDLE instance, const std::string& kodiVersion);
///   bool Start();
///
///   ...
///
///   // The pointers for on shared library exported functions
///   int (*Init)();
///   void (*Cleanup)();
///   int (*GetLength)();
/// };
///
/// CMyInstance::CMyInstance(KODI_HANDLE instance, const std::string& kodiVersion)
///   : CInstanceAudioDecoder(instance, kodiVersion)
/// {
/// }
///
/// bool CMyInstance::Start()
/// {
///   std::string lib = kodi::GetAddonPath("myLib.so");
///   if (!LoadDll(lib)) return false;
///   if (!REGISTER_DLL_SYMBOL(Init)) return false;
///   if (!REGISTER_DLL_SYMBOL(Cleanup)) return false;
///   if (!REGISTER_DLL_SYMBOL(GetLength)) return false;
///
///   Init();
///   return true;
/// }
/// ...
/// ~~~~~~~~~~~~~
///
///@{
class ATTRIBUTE_HIDDEN CDllHelper
{
public:
  //============================================================================
  /// @ingroup cpp_kodi_tools_CDllHelper
  /// @brief Class constructor.
  ///
  CDllHelper() = default;
  //----------------------------------------------------------------------------

  //============================================================================
  /// @ingroup cpp_kodi_tools_CDllHelper
  /// @brief Class destructor.
  ///
  virtual ~CDllHelper()
  {
    if (m_dll)
      dlclose(m_dll);
  }
  //----------------------------------------------------------------------------

  //============================================================================
  /// @ingroup cpp_kodi_tools_CDllHelper
  /// @brief Function to load requested library.
  ///
  /// @param[in] path The path with filename of shared library to load
  /// @return true if load was successful done
  ///
  bool LoadDll(std::string path)
  {
#if defined(TARGET_ANDROID)
    if (kodi::vfs::FileExists(path))
    {
      // Check already defined for "xbmcaltbinaddons", if yes no copy necassary.
      std::string xbmcaltbinaddons =
          kodi::vfs::TranslateSpecialProtocol("special://xbmcaltbinaddons/");
      if (path.compare(0, xbmcaltbinaddons.length(), xbmcaltbinaddons) != 0)
      {
        bool doCopy = true;
        std::string dstfile = xbmcaltbinaddons + kodi::vfs::GetFileName(path);

        kodi::vfs::FileStatus dstFileStat;
        if (kodi::vfs::StatFile(dstfile, dstFileStat))
        {
          kodi::vfs::FileStatus srcFileStat;
          if (kodi::vfs::StatFile(path, srcFileStat))
          {
            if (dstFileStat.GetSize() == srcFileStat.GetSize() &&
                dstFileStat.GetModificationTime() > srcFileStat.GetModificationTime())
              doCopy = false;
          }
        }

        if (doCopy)
        {
          kodi::Log(ADDON_LOG_DEBUG, "Caching '%s' to '%s'", path.c_str(), dstfile.c_str());
          if (!kodi::vfs::CopyFile(path, dstfile))
          {
            kodi::Log(ADDON_LOG_ERROR, "Failed to cache '%s' to '%s'", path.c_str(),
                      dstfile.c_str());
            return false;
          }
        }

        path = dstfile;
      }
    }
    else
    {
      return false;
    }
#endif

    m_dll = dlopen(path.c_str(), RTLD_LAZY);
    if (m_dll == nullptr)
    {
      kodi::Log(ADDON_LOG_ERROR, "Unable to load %s", dlerror());
      return false;
    }
    return true;
  }
  //----------------------------------------------------------------------------

  //============================================================================
  /// @ingroup cpp_kodi_tools_CDllHelper
  /// @brief Function to register requested library symbol.
  ///
  /// @warning This function should not be used, use instead the macro
  /// @ref REGISTER_DLL_SYMBOL to register the symbol pointer.
  ///
  ///
  /// Use this always via Macro, e.g.:
  /// ~~~~~~~~~~~~~{.cpp}
  /// if (!REGISTER_DLL_SYMBOL(Init))
  ///   return false;
  /// ~~~~~~~~~~~~~
  ///
  template <typename T>
  bool RegisterSymbol(T& functionPtr, const char* strFunctionPtr)
  {
    functionPtr = reinterpret_cast<T>(dlsym(m_dll, strFunctionPtr));
    if (functionPtr == nullptr)
    {
      kodi::Log(ADDON_LOG_ERROR, "Unable to assign function %s", dlerror());
      return false;
    }
    return true;
  }
  //----------------------------------------------------------------------------

private:
  void* m_dll = nullptr;
};
///@}
//------------------------------------------------------------------------------

} /* namespace tools */
} /* namespace kodi */

#endif /* __cplusplus */