1 /**
2 * Copyright (c) 2021-2024 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 "plugins/ets/runtime/ets_native_library_provider.h"
17
18 #include "plugins/ets/runtime/napi/ets_napi_invoke_interface.h"
19
20 namespace ark::ets {
LoadLibrary(EtsEnv * env,const PandaString & name)21 std::optional<std::string> NativeLibraryProvider::LoadLibrary(EtsEnv *env, const PandaString &name)
22 {
23 {
24 os::memory::ReadLockHolder lock(lock_);
25
26 auto it =
27 std::find_if(libraries_.begin(), libraries_.end(), [&name](auto &lib) { return lib.GetName() == name; });
28 if (it != libraries_.end()) {
29 return {};
30 }
31 }
32
33 auto loadRes = EtsNativeLibrary::Load(name);
34 if (!loadRes) {
35 return loadRes.Error().ToString();
36 }
37
38 const EtsNativeLibrary *lib = nullptr;
39 {
40 os::memory::WriteLockHolder lock(lock_);
41
42 auto [it, inserted] = libraries_.emplace(std::move(loadRes.Value()));
43 if (!inserted) {
44 return {};
45 }
46
47 lib = &*it;
48 }
49 ASSERT(lib != nullptr);
50
51 if (auto onLoadSymbol = lib->FindSymbol("EtsNapiOnLoad")) {
52 using EtsNapiOnLoadHandle = ets_int (*)(EtsEnv *);
53 auto onLoadHandle = reinterpret_cast<EtsNapiOnLoadHandle>(onLoadSymbol.Value());
54 ets_int etsNapiVersion = onLoadHandle(env);
55 if (!napi::CheckVersionEtsNapi(etsNapiVersion)) {
56 return {"Unsupported Ets napi version " + std::to_string(etsNapiVersion)};
57 }
58 }
59
60 return {};
61 }
62
ResolveSymbol(const PandaString & name) const63 void *NativeLibraryProvider::ResolveSymbol(const PandaString &name) const
64 {
65 os::memory::ReadLockHolder lock(lock_);
66
67 for (auto &lib : libraries_) {
68 if (auto ptr = lib.FindSymbol(name)) {
69 return ptr.Value();
70 }
71 }
72
73 return nullptr;
74 }
75 } // namespace ark::ets
76