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 <iostream>
17 #include <cstdio>
18 #include <securec.h>
19 #include "plugins/ets/runtime/napi/ets_napi.h"
20 #include "libpandabase/utils/utf.h"
21 #include "plugins/ets/runtime/napi/ets_mangle.h"
22
23 namespace ark::ets {
24
MangleString(const std::string & name)25 std::string MangleString(const std::string &name)
26 {
27 std::stringstream res;
28 const uint8_t *utf8 = ark::utf::CStringAsMutf8(name.c_str());
29 while (*utf8 != '\0') {
30 auto [ch, len] = ark::utf::ConvertMUtf8ToUtf16Pair(utf8);
31 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
32 utf8 += len;
33 if (ch == '.' || ch == '/') {
34 res << "_";
35 } else if (ch == '_') {
36 res << "_1";
37 } else if (ch == ';') {
38 res << "_2";
39 } else if (ch == '[') {
40 res << "_3";
41 } else if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
42 res << static_cast<char>(ch);
43 } else {
44 // append _0xxxx, where xxxx - unicode of symbol
45 constexpr int BUF_LEN = 16;
46 std::array<char, BUF_LEN> buf = {0};
47 auto [p_hi, p_lo] = ark::utf::SplitUtf16Pair(ch);
48 if (p_hi == 0) {
49 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg)
50 snprintf_s(buf.data(), BUF_LEN, BUF_LEN - 1, "_0%04x", p_lo);
51 } else {
52 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg)
53 snprintf_s(buf.data(), BUF_LEN, BUF_LEN - 1, "_0%04x_0%04x", p_lo, p_hi);
54 }
55 res << buf.data();
56 }
57 }
58 return res.str();
59 }
60
MangleMethodName(const std::string & className,const std::string & methodName)61 std::string MangleMethodName(const std::string &className, const std::string &methodName)
62 {
63 std::string name(className);
64 if (name[0] == 'L') {
65 name = name.substr(1, name.size() - 2U);
66 }
67 name.append(".");
68 name.append(methodName);
69 name = MangleString(name);
70 name.insert(0, "ETS_");
71 return name;
72 }
73
MangleMethodNameWithSignature(const std::string & mangledName,const std::string & signature)74 std::string MangleMethodNameWithSignature(const std::string &mangledName, const std::string &signature)
75 {
76 std::stringstream res;
77 res << mangledName << "__" << MangleString(signature);
78 return res.str();
79 }
80
81 } // namespace ark::ets
82