Coverage Report

Created: 2026-08-29 18:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/util/bfd_parser.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "util/bfd_parser.h"
19
20
#include <stdio.h>
21
#include <stdlib.h>
22
23
#include <algorithm>
24
#include <memory>
25
#include <ostream>
26
27
#include "common/logging.h"
28
29
namespace doris {
30
31
struct BfdFindCtx {
32
    BfdFindCtx(bfd_symbol** syms_, bfd_vma pc_)
33
0
            : found(false),
34
0
              syms(syms_),
35
0
              pc(pc_),
36
0
              file_name(nullptr),
37
0
              func_name(nullptr),
38
0
              lineno(0) {}
39
40
    bool found;
41
    bfd_symbol** syms;
42
    bfd_vma pc;
43
    const char* file_name;
44
    const char* func_name;
45
    unsigned int lineno;
46
};
47
48
std::mutex BfdParser::_bfd_mutex;
49
bool BfdParser::_is_bfd_inited = false;
50
51
0
static void find_addr_in_section(bfd* abfd, asection* sec, void* arg) {
52
0
    BfdFindCtx* ctx = (BfdFindCtx*)arg;
53
0
    if (ctx->found) {
54
0
        return;
55
0
    }
56
0
#ifdef bfd_get_section_flags
57
0
    if ((bfd_get_section_flags(abfd, sec) & SEC_ALLOC) == 0) {
58
0
        return;
59
0
    }
60
#else
61
    if ((bfd_section_flags(sec) & SEC_ALLOC) == 0) {
62
        return;
63
    }
64
#endif
65
0
#ifdef bfd_get_section_vma
66
0
    auto vma = bfd_get_section_vma(abfd, sec);
67
#else
68
    auto vma = bfd_section_vma(sec);
69
#endif
70
0
    if (ctx->pc < vma) {
71
0
        return;
72
0
    }
73
0
#ifdef bfd_get_section_size
74
0
    auto size = bfd_get_section_size(sec);
75
#else
76
    auto size = bfd_section_size(sec);
77
#endif
78
0
    if (ctx->pc >= vma + size) {
79
0
        return;
80
0
    }
81
0
    ctx->found = bfd_find_nearest_line(abfd, sec, ctx->syms, ctx->pc - vma, &ctx->file_name,
82
0
                                       &ctx->func_name, &ctx->lineno);
83
0
}
84
85
0
static void section_print(bfd* bfd, asection* sec, void* arg) {
86
0
    std::string* str = (std::string*)arg;
87
0
    str->append(sec->name);
88
0
    str->push_back('\n');
89
0
}
90
91
0
void BfdParser::init_bfd() {
92
0
    if (_is_bfd_inited) {
93
0
        return;
94
0
    }
95
0
    std::lock_guard<std::mutex> lock(_bfd_mutex);
96
0
    bfd_init();
97
    // The default target must match the host architecture: hardcoding
98
    // "elf64-x86-64" fails on aarch64 (libbfd there does not bundle the x86
99
    // backend) and logs a spurious error on every BE start.
100
#if defined(__aarch64__)
101
    static constexpr const char* kDefaultTarget = "elf64-littleaarch64";
102
#elif defined(__x86_64__)
103
    static constexpr const char* kDefaultTarget = "elf64-x86-64";
104
#else
105
    static constexpr const char* kDefaultTarget = nullptr;
106
#endif
107
0
    if (kDefaultTarget != nullptr && !bfd_set_default_target(kDefaultTarget)) {
108
0
        LOG(ERROR) << "set default target to " << kDefaultTarget << " failed.";
109
0
    }
110
0
    _is_bfd_inited = true;
111
0
}
112
113
0
BfdParser* BfdParser::create() {
114
0
    FILE* file = fopen("/proc/self/cmdline", "r");
115
0
    if (file == nullptr) {
116
0
        return nullptr;
117
0
    }
118
119
0
    char prog_name[1024];
120
121
0
    if (fscanf(file, "%1023s ", prog_name) != 1) {
122
0
        fclose(file);
123
0
        return nullptr;
124
0
    }
125
126
0
    fclose(file);
127
0
    std::unique_ptr<BfdParser> parser(new BfdParser(prog_name));
128
0
    if (parser->parse()) {
129
0
        return nullptr;
130
0
    }
131
0
    return parser.release();
132
0
}
133
134
0
BfdParser* BfdParser::create(const std::string& prog_name) {
135
0
    std::unique_ptr<BfdParser> parser(new BfdParser(prog_name));
136
0
    if (parser->parse()) {
137
0
        return nullptr;
138
0
    }
139
0
    return parser.release();
140
0
}
141
142
0
void BfdParser::list_targets(std::vector<std::string>* out) {
143
0
    if (!_is_bfd_inited) {
144
0
        init_bfd();
145
0
    }
146
147
0
    const char** targets = bfd_target_list();
148
0
    const char** p = targets;
149
0
    while ((*p) != nullptr) {
150
0
        out->emplace_back(*p++);
151
0
    }
152
0
    free(targets);
153
0
}
154
155
BfdParser::BfdParser(const std::string& file_name)
156
0
        : _file_name(file_name), _abfd(nullptr), _syms(nullptr), _num_symbols(0), _symbol_size(0) {
157
0
    if (!_is_bfd_inited) {
158
0
        init_bfd();
159
0
    }
160
0
}
161
162
0
BfdParser::~BfdParser() {
163
0
    if (_syms != nullptr) {
164
0
        free(_syms);
165
0
    }
166
0
    if (_abfd != nullptr) {
167
0
        bfd_close(_abfd);
168
0
    }
169
0
}
170
171
0
void BfdParser::list_sections(std::string* ss) {
172
0
    std::lock_guard<std::mutex> lock(_mutex);
173
0
    bfd_map_over_sections(_abfd, section_print, (void*)ss);
174
0
}
175
176
0
static void list_matching_formats(char** p, std::string* message) {
177
0
    if (!p || !*p) {
178
0
        return;
179
0
    }
180
0
    message->append(": Matching formats: ");
181
0
    while (*p) {
182
0
        message->append(*p++);
183
0
    }
184
0
    message->push_back('\n');
185
0
}
186
187
0
int BfdParser::open_bfd() {
188
0
    _abfd = bfd_openr(_file_name.c_str(), nullptr);
189
0
    if (_abfd == nullptr) {
190
0
        LOG(WARNING) << "bfd_openr failed because errmsg=" << bfd_errmsg(bfd_get_error());
191
0
        return -1;
192
0
    }
193
0
    if (bfd_check_format(_abfd, bfd_archive)) {
194
0
        LOG(WARNING) << "bfd_check_format for archive failed because errmsg="
195
0
                     << bfd_errmsg(bfd_get_error());
196
0
        return -1;
197
0
    }
198
199
0
    char** matches = nullptr;
200
0
    if (!bfd_check_format_matches(_abfd, bfd_object, &matches)) {
201
0
        if (bfd_get_error() == bfd_error_file_ambiguously_recognized) {
202
0
            std::string message = _file_name;
203
0
            list_matching_formats(matches, &message);
204
0
            free(matches);
205
0
            LOG(WARNING) << "bfd_check_format_matches failed because errmsg="
206
0
                         << bfd_errmsg(bfd_get_error()) << " and " << message;
207
0
        } else {
208
0
            LOG(WARNING) << "bfd_check_format_matches failed because errmsg="
209
0
                         << bfd_errmsg(bfd_get_error());
210
0
        }
211
0
        return -1;
212
0
    }
213
214
0
    return 0;
215
0
}
216
217
0
int BfdParser::load_symbols() {
218
0
    if ((bfd_get_file_flags(_abfd) & HAS_SYMS) == 0) {
219
        // No need to load symbols;
220
0
        return 0;
221
0
    }
222
0
    _num_symbols = bfd_read_minisymbols(_abfd, FALSE, (void**)&_syms, &_symbol_size);
223
0
    if (_num_symbols == 0) {
224
0
        _num_symbols =
225
0
                bfd_read_minisymbols(_abfd, TRUE /* dynamic */, (void**)&_syms, &_symbol_size);
226
0
    }
227
0
    if (_num_symbols == 0) {
228
0
        LOG(WARNING) << "Load symbols failed because errmsg=" << bfd_errmsg(bfd_get_error());
229
0
        return -1;
230
0
    }
231
0
    return 0;
232
0
}
233
234
0
int BfdParser::parse() {
235
0
    int ret = open_bfd();
236
0
    if (ret != 0) {
237
0
        LOG(WARNING) << "open bfd failed.";
238
0
        return ret;
239
0
    }
240
241
0
    ret = load_symbols();
242
0
    if (ret != 0) {
243
0
        LOG(WARNING) << "Load symbols failed.";
244
0
        return ret;
245
0
    }
246
247
0
    return 0;
248
0
}
249
250
int BfdParser::decode_address(const char* str, const char** end, std::string* file_name,
251
0
                              std::string* func_name, unsigned int* lineno) {
252
0
    bfd_vma pc = bfd_scan_vma(str, end, 16);
253
0
    BfdFindCtx ctx(_syms, pc);
254
255
0
    std::lock_guard<std::mutex> lock(_mutex);
256
0
    bfd_map_over_sections(_abfd, find_addr_in_section, (void*)&ctx);
257
0
    if (!ctx.found) {
258
0
        file_name->append("??");
259
0
        func_name->append("??");
260
0
        return -1;
261
0
    }
262
    // demangle function
263
0
    if (ctx.func_name != nullptr) {
264
0
#define DMGL_PARAMS (1 << 0)
265
0
#define DMGL_ANSI (1 << 1)
266
0
        char* demangled_name = bfd_demangle(_abfd, ctx.func_name, DMGL_ANSI | DMGL_PARAMS);
267
0
        if (demangled_name != nullptr) {
268
0
            func_name->append(demangled_name);
269
0
            free(demangled_name);
270
0
        } else {
271
0
            func_name->append(ctx.func_name);
272
0
        }
273
0
    } else {
274
0
        func_name->append("??");
275
0
    }
276
    // file_name
277
0
    if (ctx.file_name != nullptr) {
278
0
        file_name->append(ctx.file_name);
279
0
    } else {
280
0
        file_name->append("??");
281
0
    }
282
0
    *lineno = ctx.lineno;
283
0
    return 0;
284
0
}
285
286
} // namespace doris