1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <cxxabi.h>
18 #include <stdlib.h>
19
20 #include <string>
21
22 #include <rustc_demangle.h>
23
24 #include <unwindstack/Demangle.h>
25
26 namespace unwindstack {
27
Demangle(const char * name,size_t length)28 static std::string Demangle(const char* name, size_t length) {
29 if (length < 2 || name[0] != '_') {
30 return name;
31 }
32
33 char* demangled_str = nullptr;
34 if (name[1] == 'Z') {
35 // Try to demangle C++ name.
36 demangled_str = abi::__cxa_demangle(name, nullptr, nullptr, nullptr);
37 } else if (name[1] == 'R') {
38 // Try to demangle rust name.
39 demangled_str = rustc_demangle(name, nullptr, nullptr, nullptr);
40 }
41
42 if (demangled_str == nullptr) {
43 return name;
44 }
45
46 std::string demangled_name(demangled_str);
47 free(demangled_str);
48 return demangled_name;
49 }
50
DemangleNameIfNeeded(const std::string & name)51 std::string DemangleNameIfNeeded(const std::string& name) {
52 // This is special, the Android linker has functions of the form __dl_XXX,
53 // where the XX might be a mangled name. Try to demangle that part and
54 // add the __dl_ back.
55 if (name.starts_with("__dl_")) {
56 return "__dl_" + Demangle(&name[5], name.length() - 5);
57 }
58
59 return Demangle(name.c_str(), name.length());
60 }
61
62 } // namespace unwindstack
63