xref: /aosp_15_r20/external/stg/elf_dwarf_handle.h (revision 9e3b08ae94a55201065475453d799e8b1378bea6)
1 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
2 // -*- mode: C++ -*-
3 //
4 // Copyright 2022-2024 Google LLC
5 //
6 // Licensed under the Apache License v2.0 with LLVM Exceptions (the
7 // "License"); you may not use this file except in compliance with the
8 // License.  You may obtain a copy of the License at
9 //
10 //     https://llvm.org/LICENSE.txt
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
18 // Author: Aleksei Vetrov
19 
20 #ifndef STG_ELF_DWARF_HANDLE_H_
21 #define STG_ELF_DWARF_HANDLE_H_
22 
23 #include <elfutils/libdw.h>
24 #include <elfutils/libdwfl.h>
25 #include <libelf.h>
26 
27 #include <cstddef>
28 #include <functional>
29 #include <memory>
30 #include <string>
31 
32 namespace stg {
33 
34 class ElfDwarfHandle {
35  public:
36   explicit ElfDwarfHandle(const std::string& path);
37   ElfDwarfHandle(char* data, size_t size);
38 
39   Elf& GetElf();
40   Dwarf* GetDwarf();  // Returns nullptr if DWARF is not available.
41 
42  private:
43   struct DwflDeleter {
operatorDwflDeleter44     void operator()(Dwfl* dwfl) {
45       dwfl_end(dwfl);
46     }
47   };
48   using DwflUniquePtr = std::unique_ptr<Dwfl, DwflDeleter>;
49 
50   ElfDwarfHandle(const char* module_name,
51                  const std::function<Dwfl_Module*()>& add_module);
52 
53   DwflUniquePtr dwfl_;
54   // Lifetime of Dwfl_Module is controlled by Dwfl.
55   Dwfl_Module* dwfl_module_ = nullptr;
56 };
57 
58 }  // namespace stg
59 
60 
61 #endif  // STG_ELF_DWARF_HANDLE_H_
62