xref: /aosp_15_r20/external/perfetto/src/trace_processor/demangle.cc (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 /*
2  * Copyright (C) 2022 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 "perfetto/ext/trace_processor/demangle.h"
18 
19 #include <string.h>
20 #include <string>
21 
22 #include "perfetto/base/build_config.h"
23 
24 #if PERFETTO_BUILDFLAG(PERFETTO_LLVM_DEMANGLE)
25 #include "llvm/Demangle/Demangle.h"
26 #elif !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
27 #include <cxxabi.h>
28 #endif
29 
30 namespace perfetto {
31 namespace trace_processor {
32 namespace demangle {
33 
34 // Implementation depends on platform and build config. If llvm demangling
35 // sources are available, use them. That is the most portable and handles more
36 // than just Itanium mangling (e.g. Rust's _R scheme). Otherwise use the c++
37 // standard library demangling if it implements the appropriate ABI. This
38 // excludes Windows builds, where we therefore never demangle.
39 // TODO(rsavitski): consider reimplementing llvm::demangle inline as it's
40 // wrapping in std::strings a set of per-scheme demangling functions that
41 // operate on C strings. Right now we're introducing yet another layer that
42 // undoes that conversion.
Demangle(const char * mangled_name)43 std::unique_ptr<char, base::FreeDeleter> Demangle(const char* mangled_name) {
44 #if PERFETTO_BUILDFLAG(PERFETTO_LLVM_DEMANGLE)
45   std::string input(mangled_name);
46   std::string demangled = llvm::demangle(input);
47   if (demangled == input)
48     return nullptr;  // demangling unsuccessful
49 
50   std::unique_ptr<char, base::FreeDeleter> output(
51       static_cast<char*>(malloc(demangled.size() + 1)));
52   if (!output)
53     return nullptr;
54   memcpy(output.get(), demangled.c_str(), demangled.size() + 1);
55   return output;
56 
57 #elif !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
58   int ignored = 0;
59   return std::unique_ptr<char, base::FreeDeleter>(
60       abi::__cxa_demangle(mangled_name, nullptr, nullptr, &ignored));
61 
62 #else
63   return nullptr;
64 #endif
65 }
66 
67 }  // namespace demangle
68 }  // namespace trace_processor
69 }  // namespace perfetto
70