• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "plugin.h"
17 #include <utility>
18 #include "hilog/log.h"
19 #include "impl_class_mgr.h"
20 #include "json.hpp"
21 #include "json_helper.h"
22 #include "log_tags.h"
23 #include "platform_adp.h"
24 #include "singleton.h"
25 #ifdef _WIN32
26 #include <windows.h>
27 HMODULE hDll = NULL;
28 #endif
29 
30 namespace OHOS {
31 namespace MultimediaPlugin {
32 using nlohmann::json;
33 using std::istream;
34 using std::istringstream;
35 using std::recursive_mutex;
36 using std::size_t;
37 using std::string;
38 using std::weak_ptr;
39 using namespace OHOS::HiviewDFX;
40 
41 enum class VersionParseStep : int32_t { STEP_MAJOR = 0, STEP_MINOR, STEP_MICRO, STEP_NANO, STEP_FINISHED };
42 
43 struct VersionNum {
44     uint16_t major = 0;
45     uint16_t minor = 0;
46     uint16_t micro = 0;
47     uint16_t nano = 0;
48 };
49 
50 static constexpr HiLogLabel LABEL = { LOG_CORE, LOG_TAG_DOMAIN_ID_PLUGIN, "Plugin" };
51 
Plugin()52 Plugin::Plugin()
53     : platformAdp_(DelayedRefSingleton<PlatformAdp>::GetInstance()),
54       implClassMgr_(DelayedRefSingleton<ImplClassMgr>::GetInstance()) {}
55 
~Plugin()56 Plugin::~Plugin()
57 {
58     std::unique_lock<std::recursive_mutex> guard(dynDataLock_);
59     if (refNum_ != 0) {
60         // this situation does not happen in design.
61         // the process context can guarantee that this will not happen.
62         // the judgment statement here is for protection and positioning purposes only.
63         HiLog::Error(LABEL, "release plugin: refNum: %{public}u.", refNum_);
64     }
65 
66     implClassMgr_.DeleteClass(plugin_);
67     FreeLibrary();
68 }
69 
Register(istream & metadata,string && libraryPath,weak_ptr<Plugin> & plugin)70 uint32_t Plugin::Register(istream &metadata, string &&libraryPath, weak_ptr<Plugin> &plugin)
71 {
72     std::unique_lock<std::recursive_mutex> guard(dynDataLock_);
73     if (state_ != PluginState::PLUGIN_STATE_UNREGISTER) {
74         guard.unlock();
75         HiLog::Error(LABEL, "repeat registration.");
76         return ERR_INTERNAL;
77     }
78 
79     auto ret = RegisterMetadata(metadata, plugin);
80     if (ret != SUCCESS) {
81         guard.unlock();
82         HiLog::Error(LABEL, "failed to register metadata, ERRNO: %{public}u.", ret);
83         return ret;
84     }
85 
86     libraryPath_ = std::move(libraryPath);
87     plugin_ = plugin;
88     state_ = PluginState::PLUGIN_STATE_REGISTERED;
89     return SUCCESS;
90 }
91 
CfiStartFunc_(PluginStartFunc startFunc_)92 bool CfiStartFunc_(PluginStartFunc startFunc_) __attribute__((no_sanitize("cfi")))
93 {
94     return startFunc_();
95 }
96 
Ref()97 uint32_t Plugin::Ref()
98 {
99     // once the client make a ref, it can use the plugin at any time,
100     // so we do the necessary preparations here.
101     std::unique_lock<std::recursive_mutex> guard(dynDataLock_);
102     if (state_ == PluginState::PLUGIN_STATE_REGISTERED) {
103         if (ResolveLibrary() != SUCCESS) {
104             guard.unlock();
105             HiLog::Error(LABEL, "failed to resolve library.");
106             return ERR_GENERAL;
107         }
108         state_ = PluginState::PLUGIN_STATE_RESOLVED;
109     }
110 
111     if (state_ == PluginState::PLUGIN_STATE_RESOLVED) {
112         // maybe asynchronous, or for reduce the locking time
113         state_ = PluginState::PLUGIN_STATE_STARTING;
114         if (!CfiStartFunc_(startFunc_)) {
115             HiLog::Error(LABEL, "failed to start plugin.");
116             FreeLibrary();
117             state_ = PluginState::PLUGIN_STATE_REGISTERED;
118             return ERR_GENERAL;
119         }
120         state_ = PluginState::PLUGIN_STATE_ACTIVE;
121     }
122 
123     if (state_ != PluginState::PLUGIN_STATE_ACTIVE) {
124         HiLog::Error(LABEL, "plugin ref: state error, state: %{public}d.", state_);
125         return ERR_GENERAL;
126     }
127 
128     ++refNum_;
129     HiLog::Debug(LABEL, "plugin refNum: %{public}d.", refNum_);
130     return SUCCESS;
131 }
132 
DeRef()133 void Plugin::DeRef()
134 {
135     std::unique_lock<std::recursive_mutex> guard(dynDataLock_);
136     if (refNum_ == 0) {
137         // this situation does not happen in design.
138         // the process context can guarantee that this will not happen.
139         // the judgment statement here is for protection and positioning purposes only.
140         guard.unlock();
141         HiLog::Error(LABEL, "DeRef while RefNum is zero.");
142         return;
143     }
144 
145     --refNum_;
146     HiLog::Debug(LABEL, "plugin refNum: %{public}d.", refNum_);
147 }
148 
Block()149 void Plugin::Block()
150 {
151     // used to protect against business interruptions during plugin upgrades.
152     // after the plugin is upgraded, if the original .so is being used,
153     // it cannot be released immediately and should be locked,
154     // and the subsequent requests are migrated to the new .so.
155     std::unique_lock<std::recursive_mutex> guard(dynDataLock_);
156     blocked_ = true;
157 }
158 
Unblock()159 void Plugin::Unblock()
160 {
161     std::unique_lock<std::recursive_mutex> guard(dynDataLock_);
162     blocked_ = false;
163 }
164 
GetCreateFunc()165 PluginCreateFunc Plugin::GetCreateFunc()
166 {
167     std::unique_lock<std::recursive_mutex> guard(dynDataLock_);
168     if ((state_ != PluginState::PLUGIN_STATE_ACTIVE) || (refNum_ == 0)) {
169         // In this case, we can't guarantee that the pointer is lasting valid.
170         HiLog::Error(LABEL, "failed to get create func, State: %{public}d, RefNum: %{public}u.", state_, refNum_);
171         return nullptr;
172     }
173 
174     return createFunc_;
175 }
176 
GetLibraryPath() const177 const string &Plugin::GetLibraryPath() const
178 {
179     return libraryPath_;
180 }
181 
GetPackageName() const182 const string &Plugin::GetPackageName() const
183 {
184     return packageName_;
185 }
186 
187 // ------------------------------- private method -------------------------------
ResolveLibrary()188 uint32_t Plugin::ResolveLibrary()
189 {
190     std::string pluginStartSymbol = "PluginExternalStart";
191     std::string pluginStopSymbol = "PluginExternalStop";
192     std::string pluginCreateSymbol = "PluginExternalCreate";
193 
194 #ifdef _WIN32
195     hDll = platformAdp_.AdpLoadLibrary(libraryPath_);
196     if (hDll == NULL) {
197         HiLog::Error(LABEL, "failed to load library.");
198         return ERR_GENERAL;
199     }
200 
201     startFunc_ = (PluginStartFunc)platformAdp_.AdpGetSymAddress(hDll, pluginStartSymbol);
202     stopFunc_ = (PluginStopFunc)platformAdp_.AdpGetSymAddress(hDll, pluginStopSymbol);
203     createFunc_ = (PluginCreateFunc)platformAdp_.AdpGetSymAddress(hDll, pluginCreateSymbol);
204     if (startFunc_ == NULL || stopFunc_ == NULL || createFunc_ == NULL) {
205         HiLog::Error(LABEL, "failed to get export symbol for the plugin.");
206         FreeLibrary();
207         return ERR_GENERAL;
208     }
209 
210     return SUCCESS;
211 #else
212     handle_ = platformAdp_.LoadLibrary(libraryPath_);
213     if (handle_ == nullptr) {
214         HiLog::Error(LABEL, "failed to load library.");
215         return ERR_GENERAL;
216     }
217 
218     startFunc_ = (PluginStartFunc)platformAdp_.GetSymAddress(handle_, pluginStartSymbol);
219     stopFunc_ = (PluginStopFunc)platformAdp_.GetSymAddress(handle_, pluginStopSymbol);
220     createFunc_ = (PluginCreateFunc)platformAdp_.GetSymAddress(handle_, pluginCreateSymbol);
221     if (startFunc_ == nullptr || stopFunc_ == nullptr || createFunc_ == nullptr) {
222         HiLog::Error(LABEL, "failed to get export symbol for the plugin.");
223         FreeLibrary();
224         return ERR_GENERAL;
225     }
226 
227     return SUCCESS;
228 #endif
229 }
230 
FreeLibrary()231 void Plugin::FreeLibrary()
232 {
233 #ifdef _WIN32
234     if (state_ == PluginState::PLUGIN_STATE_STARTING || state_ == PluginState::PLUGIN_STATE_ACTIVE) {
235         if (stopFunc_ != NULL) {
236             stopFunc_();
237         }
238     }
239     if (handle_ == NULL) {
240         return;
241     }
242     platformAdp_.AdpFreeLibrary(hDll);
243     hDll = NULL;
244     startFunc_ = NULL;
245     stopFunc_ = NULL;
246     createFunc_ = NULL;
247 #else
248     if (state_ == PluginState::PLUGIN_STATE_STARTING || state_ == PluginState::PLUGIN_STATE_ACTIVE) {
249         if (stopFunc_ != nullptr) {
250             stopFunc_();
251         }
252     }
253 
254     if (handle_ == nullptr) {
255         return;
256     }
257 
258     platformAdp_.FreeLibrary(handle_);
259     handle_ = nullptr;
260     startFunc_ = nullptr;
261     stopFunc_ = nullptr;
262     createFunc_ = nullptr;
263 #endif
264 }
265 
RegisterMetadata(istream & metadata,weak_ptr<Plugin> & plugin)266 uint32_t Plugin::RegisterMetadata(istream &metadata, weak_ptr<Plugin> &plugin)
267 {
268     json root;
269     metadata >> root;
270     if (JsonHelper::GetStringValue(root, "packageName", packageName_) != SUCCESS) {
271         HiLog::Error(LABEL, "read packageName failed.");
272         return ERR_INVALID_PARAMETER;
273     }
274 
275     string targetVersion;
276     if (JsonHelper::GetStringValue(root, "targetVersion", targetVersion) != SUCCESS) {
277         HiLog::Error(LABEL, "read targetVersion failed.");
278         return ERR_INVALID_PARAMETER;
279     }
280     uint32_t ret = CheckTargetVersion(targetVersion);
281     if (ret != SUCCESS) {
282         // target version is not compatible
283         HiLog::Error(LABEL, "check targetVersion failed, Version: %{public}s, ERRNO: %{public}u.",
284                      targetVersion.c_str(), ret);
285         return ret;
286     }
287 
288     if (JsonHelper::GetStringValue(root, "version", version_) != SUCCESS) {
289         HiLog::Error(LABEL, "read version failed.");
290         return ERR_INVALID_PARAMETER;
291     }
292     VersionNum versionNum;
293     ret = AnalyzeVersion(version_, versionNum);
294     if (ret != SUCCESS) {
295         HiLog::Error(LABEL, "check version failed, Version: %{public}s, ERRNO: %{public}u.", version_.c_str(), ret);
296         return ret;
297     }
298 
299     size_t classNum;
300     if (JsonHelper::GetArraySize(root, "classes", classNum) != SUCCESS) {
301         HiLog::Error(LABEL, "get array size of classes failed.");
302         return ERR_INVALID_PARAMETER;
303     }
304     HiLog::Debug(LABEL, "parse class num: %{public}zu.", classNum);
305     for (size_t i = 0; i < classNum; i++) {
306         const json &classInfo = root["classes"][i];
307         if (implClassMgr_.AddClass(plugin, classInfo) != SUCCESS) {
308             HiLog::Error(LABEL, "failed to add class, index: %{public}zu.", i);
309             continue;
310         }
311     }
312 
313     return SUCCESS;
314 }
315 
CheckTargetVersion(const string & targetVersion)316 uint32_t Plugin::CheckTargetVersion(const string &targetVersion)
317 {
318     VersionNum versionNum;
319     auto ret = AnalyzeVersion(targetVersion, versionNum);
320     if (ret != SUCCESS) {
321         HiLog::Error(LABEL, "failed to analyze version, ERRNO: %{public}u.", ret);
322         return ret;
323     }
324 
325     return SUCCESS;
326 }
327 
AnalyzeVersion(const string & versionInfo,VersionNum & versionNum)328 uint32_t Plugin::AnalyzeVersion(const string &versionInfo, VersionNum &versionNum)
329 {
330     VersionParseStep step = VersionParseStep::STEP_MAJOR;
331     istringstream versionInput(versionInfo);
332     uint16_t versionArray[VERSION_ARRAY_SIZE] = { 0 };  // major, minor, micro, nano.
333     string tmp;
334 
335     while (getline(versionInput, tmp, '.')) {
336         auto ret = ExecuteVersionAnalysis(tmp, step, versionArray);
337         if (ret != SUCCESS) {
338             HiLog::Error(LABEL, "failed to execute version analysis, ERRNO: %{public}u.", ret);
339             return ret;
340         }
341     }
342 
343     if (step == VersionParseStep::STEP_NANO) {
344         // we treat nano version as optional, and default 0.
345         HiLog::Debug(LABEL, "default nano version 0.");
346         versionArray[VERSION_NANO_INDEX] = 0;
347         step = VersionParseStep::STEP_FINISHED;
348     }
349 
350     if (step != VersionParseStep::STEP_FINISHED) {
351         HiLog::Error(LABEL, "analysis version failed, step = %{public}d.", step);
352         return ERR_INVALID_PARAMETER;
353     }
354 
355     versionNum.major = versionArray[VERSION_MAJOR_INDEX];
356     versionNum.minor = versionArray[VERSION_MINOR_INDEX];
357     versionNum.micro = versionArray[VERSION_MICRO_INDEX];
358     versionNum.nano = versionArray[VERSION_NANO_INDEX];
359 
360     HiLog::Debug(LABEL, "analysis result: %{public}u.%{public}u.%{public}u.%{public}u.", versionNum.major,
361                  versionNum.minor, versionNum.micro, versionNum.nano);
362 
363     return SUCCESS;
364 }
365 
ExecuteVersionAnalysis(const string & input,VersionParseStep & step,uint16_t (& versionNum)[VERSION_ARRAY_SIZE])366 uint32_t Plugin::ExecuteVersionAnalysis(const string &input, VersionParseStep &step,
367                                         uint16_t (&versionNum)[VERSION_ARRAY_SIZE])
368 {
369     switch (step) {
370         case VersionParseStep::STEP_MAJOR: {
371             auto ret = GetUint16ValueFromDecimal(input, versionNum[VERSION_MAJOR_INDEX]);
372             if (ret != SUCCESS) {
373                 HiLog::Error(LABEL, "read major version failed, input: %{public}s, ERRNO: %{public}u.", input.c_str(),
374                              ret);
375                 return ret;
376             }
377             step = VersionParseStep::STEP_MINOR;
378             break;
379         }
380         case VersionParseStep::STEP_MINOR: {
381             auto ret = GetUint16ValueFromDecimal(input, versionNum[VERSION_MINOR_INDEX]);
382             if (ret != SUCCESS) {
383                 HiLog::Error(LABEL, "read minor version failed, input: %{public}s, ERRNO: %{public}u.", input.c_str(),
384                              ret);
385                 return ret;
386             }
387             step = VersionParseStep::STEP_MICRO;
388             break;
389         }
390         case VersionParseStep::STEP_MICRO: {
391             auto ret = GetUint16ValueFromDecimal(input, versionNum[VERSION_MICRO_INDEX]);
392             if (ret != SUCCESS) {
393                 HiLog::Error(LABEL, "read micro version failed, input: %{public}s, ERRNO: %{public}u.", input.c_str(),
394                              ret);
395                 return ret;
396             }
397             step = VersionParseStep::STEP_NANO;
398             break;
399         }
400         case VersionParseStep::STEP_NANO: {
401             auto ret = GetUint16ValueFromDecimal(input, versionNum[VERSION_NANO_INDEX]);
402             if (ret != SUCCESS) {
403                 HiLog::Error(LABEL, "read nano version failed, input: %{public}s, ERRNO: %{public}u.", input.c_str(),
404                              ret);
405                 return ret;
406             }
407             step = VersionParseStep::STEP_FINISHED;
408             break;
409         }
410         default: {
411             HiLog::Error(LABEL, "read redundant version data, input: %{public}s.", input.c_str());
412             return ERR_INVALID_PARAMETER;
413         }
414     }
415 
416     return SUCCESS;
417 }
418 
GetUint16ValueFromDecimal(const string & source,uint16_t & result)419 uint32_t Plugin::GetUint16ValueFromDecimal(const string &source, uint16_t &result)
420 {
421     if (source.empty() || source.size() > UINT16_MAX_DECIMAL_DIGITS) {
422         HiLog::Error(LABEL, "invalid string of uint16: %{public}s.", source.c_str());
423         return ERR_INVALID_PARAMETER;
424     }
425 
426     // determine if all characters are numbers.
427     for (const auto &character : source) {
428         if (character < '0' || character > '9') {
429             HiLog::Error(LABEL, "character out of the range of digital: %{public}s.", source.c_str());
430             return ERR_INVALID_PARAMETER;
431         }
432     }
433 
434     unsigned long tmp = stoul(source);
435     if (tmp > UINT16_MAX_VALUE) {
436         HiLog::Error(LABEL, "result out of the range of uint16: %{public}s.", source.c_str());
437         return ERR_INVALID_PARAMETER;
438     }
439 
440     result = static_cast<uint16_t>(tmp);
441     return SUCCESS;
442 }
443 } // namespace MultimediaPlugin
444 } // namespace OHOS
445