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