summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibDebug/Dwarf/LineProgram.cpp
blob: 16c5bc25edd874dd2f9144c9166a7c363210509c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
 * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "LineProgram.h"
#include <AK/Debug.h>
#include <AK/DeprecatedString.h>
#include <AK/Function.h>
#include <AK/LEB128.h>
#include <AK/StringBuilder.h>
#include <LibDebug/Dwarf/DwarfInfo.h>

namespace Debug::Dwarf {

LineProgram::LineProgram(DwarfInfo& dwarf_info, SeekableStream& stream)
    : m_dwarf_info(dwarf_info)
    , m_stream(stream)
{
    m_unit_offset = m_stream.tell().release_value_but_fixme_should_propagate_errors();
    parse_unit_header().release_value_but_fixme_should_propagate_errors();
    parse_source_directories().release_value_but_fixme_should_propagate_errors();
    parse_source_files().release_value_but_fixme_should_propagate_errors();
    run_program().release_value_but_fixme_should_propagate_errors();
}

ErrorOr<void> LineProgram::parse_unit_header()
{
    m_unit_header = TRY(m_stream.read_value<LineProgramUnitHeader32>());

    VERIFY(m_unit_header.version() >= MIN_DWARF_VERSION && m_unit_header.version() <= MAX_DWARF_VERSION);
    VERIFY(m_unit_header.opcode_base() <= sizeof(m_unit_header.std_opcode_lengths) / sizeof(m_unit_header.std_opcode_lengths[0]) + 1);

    dbgln_if(DWARF_DEBUG, "unit length: {}", m_unit_header.length());
    return {};
}

ErrorOr<void> LineProgram::parse_path_entries(Function<void(PathEntry& entry)> callback, PathListType list_type)
{
    if (m_unit_header.version() >= 5) {
        auto path_entry_format_count = TRY(m_stream.read_value<u8>());

        Vector<PathEntryFormat> format_descriptions;

        for (u8 i = 0; i < path_entry_format_count; i++) {
            UnderlyingType<ContentType> content_type;
            TRY(LEB128::read_unsigned(m_stream, content_type));

            UnderlyingType<AttributeDataForm> data_form;
            TRY(LEB128::read_unsigned(m_stream, data_form));

            format_descriptions.empend(static_cast<ContentType>(content_type), static_cast<AttributeDataForm>(data_form));
        }

        size_t paths_count = 0;
        TRY(LEB128::read_unsigned(m_stream, paths_count));

        for (size_t i = 0; i < paths_count; i++) {
            PathEntry entry;
            for (auto& format_description : format_descriptions) {
                auto value = TRY(m_dwarf_info.get_attribute_value(format_description.form, 0, m_stream));
                switch (format_description.type) {
                case ContentType::Path:
                    entry.path = TRY(value.as_string());
                    break;
                case ContentType::DirectoryIndex:
                    entry.directory_index = value.as_unsigned();
                    break;
                default:
                    dbgln_if(DWARF_DEBUG, "Unhandled path list attribute: {}", to_underlying(format_description.type));
                }
            }
            callback(entry);
        }
    } else {
        while (true) {
            StringBuilder builder;
            while (auto c = TRY(m_stream.read_value<char>()))
                TRY(builder.try_append(c));
            auto path = builder.to_deprecated_string();
            if (path.length() == 0)
                break;
            dbgln_if(DWARF_DEBUG, "path: {}", path);
            PathEntry entry;
            entry.path = path;
            if (list_type == PathListType::Filenames) {
                size_t directory_index = 0;
                TRY(LEB128::read_unsigned(m_stream, directory_index));
                size_t _unused = 0;
                TRY(LEB128::read_unsigned(m_stream, _unused)); // skip modification time
                TRY(LEB128::read_unsigned(m_stream, _unused)); // skip file size
                entry.directory_index = directory_index;
                dbgln_if(DWARF_DEBUG, "file: {}, directory index: {}", path, directory_index);
            }
            callback(entry);
        }
    }

    return {};
}

ErrorOr<void> LineProgram::parse_source_directories()
{
    if (m_unit_header.version() < 5) {
        m_source_directories.append(".");
    }

    TRY(parse_path_entries([this](PathEntry& entry) {
        m_source_directories.append(entry.path);
    },
        PathListType::Directories));

    return {};
}

ErrorOr<void> LineProgram::parse_source_files()
{
    if (m_unit_header.version() < 5) {
        m_source_files.append({ ".", 0 });
    }

    TRY(parse_path_entries([this](PathEntry& entry) {
        m_source_files.append({ entry.path, entry.directory_index });
    },
        PathListType::Filenames));

    return {};
}

void LineProgram::append_to_line_info()
{
    dbgln_if(DWARF_DEBUG, "appending line info: {:p}, {}:{}", m_address, m_source_files[m_file_index].name, m_line);
    if (!m_is_statement)
        return;

    if (m_file_index >= m_source_files.size())
        return;

    auto const& directory = m_source_directories[m_source_files[m_file_index].directory_index];

    StringBuilder full_path(directory.length() + m_source_files[m_file_index].name.length() + 1);
    full_path.append(directory);
    full_path.append('/');
    full_path.append(m_source_files[m_file_index].name);

    m_lines.append({ m_address, DeprecatedFlyString { full_path.string_view() }, m_line });
}

void LineProgram::reset_registers()
{
    m_address = 0;
    m_line = 1;
    m_file_index = 1;
    m_is_statement = m_unit_header.default_is_stmt() == 1;
}

ErrorOr<void> LineProgram::handle_extended_opcode()
{
    size_t length = 0;
    TRY(LEB128::read_unsigned(m_stream, length));

    auto sub_opcode = TRY(m_stream.read_value<u8>());

    switch (sub_opcode) {
    case ExtendedOpcodes::EndSequence: {
        append_to_line_info();
        reset_registers();
        break;
    }
    case ExtendedOpcodes::SetAddress: {
        VERIFY(length == sizeof(size_t) + 1);
        m_address = TRY(m_stream.read_value<FlatPtr>());
        dbgln_if(DWARF_DEBUG, "SetAddress: {:p}", m_address);
        break;
    }
    case ExtendedOpcodes::SetDiscriminator: {
        dbgln_if(DWARF_DEBUG, "SetDiscriminator");
        size_t discriminator;
        TRY(LEB128::read_unsigned(m_stream, discriminator));
        break;
    }
    default:
        dbgln("Encountered unknown sub opcode {} at stream offset {:p}", sub_opcode, TRY(m_stream.tell()));
        VERIFY_NOT_REACHED();
    }

    return {};
}
ErrorOr<void> LineProgram::handle_standard_opcode(u8 opcode)
{
    switch (opcode) {
    case StandardOpcodes::Copy: {
        append_to_line_info();
        break;
    }
    case StandardOpcodes::AdvancePc: {
        size_t operand = 0;
        TRY(LEB128::read_unsigned(m_stream, operand));
        size_t delta = operand * m_unit_header.min_instruction_length();
        dbgln_if(DWARF_DEBUG, "AdvancePC by: {} to: {:p}", delta, m_address + delta);
        m_address += delta;
        break;
    }
    case StandardOpcodes::SetFile: {
        size_t new_file_index = 0;
        TRY(LEB128::read_unsigned(m_stream, new_file_index));
        dbgln_if(DWARF_DEBUG, "SetFile: new file index: {}", new_file_index);
        m_file_index = new_file_index;
        break;
    }
    case StandardOpcodes::SetColumn: {
        // not implemented
        dbgln_if(DWARF_DEBUG, "SetColumn");
        size_t new_column;
        TRY(LEB128::read_unsigned(m_stream, new_column));

        break;
    }
    case StandardOpcodes::AdvanceLine: {
        ssize_t line_delta;
        TRY(LEB128::read_signed(m_stream, line_delta));
        VERIFY(line_delta >= 0 || m_line >= (size_t)(-line_delta));
        m_line += line_delta;
        dbgln_if(DWARF_DEBUG, "AdvanceLine: {}", m_line);
        break;
    }
    case StandardOpcodes::NegateStatement: {
        dbgln_if(DWARF_DEBUG, "NegateStatement");
        m_is_statement = !m_is_statement;
        break;
    }
    case StandardOpcodes::ConstAddPc: {
        u8 adjusted_opcode = 255 - m_unit_header.opcode_base();
        ssize_t address_increment = (adjusted_opcode / m_unit_header.line_range()) * m_unit_header.min_instruction_length();
        address_increment *= m_unit_header.min_instruction_length();
        dbgln_if(DWARF_DEBUG, "ConstAddPc: advance pc by: {} to: {}", address_increment, (m_address + address_increment));
        m_address += address_increment;
        break;
    }
    case StandardOpcodes::SetIsa: {
        size_t isa;
        TRY(LEB128::read_unsigned(m_stream, isa));
        dbgln_if(DWARF_DEBUG, "SetIsa: {}", isa);
        break;
    }
    case StandardOpcodes::FixAdvancePc: {
        auto delta = TRY(m_stream.read_value<u16>());
        dbgln_if(DWARF_DEBUG, "FixAdvancePC by: {} to: {:p}", delta, m_address + delta);
        m_address += delta;
        break;
    }
    case StandardOpcodes::SetBasicBlock: {
        m_basic_block = true;
        break;
    }
    case StandardOpcodes::SetPrologueEnd: {
        m_prologue_end = true;
        break;
    }
    default:
        dbgln("Unhandled LineProgram opcode {}", opcode);
        VERIFY_NOT_REACHED();
    }

    return {};
}
void LineProgram::handle_special_opcode(u8 opcode)
{
    u8 adjusted_opcode = opcode - m_unit_header.opcode_base();
    ssize_t address_increment = (adjusted_opcode / m_unit_header.line_range()) * m_unit_header.min_instruction_length();
    ssize_t line_increment = m_unit_header.line_base() + (adjusted_opcode % m_unit_header.line_range());

    m_address += address_increment;
    m_line += line_increment;

    if constexpr (DWARF_DEBUG) {
        dbgln("Special adjusted_opcode: {}, address_increment: {}, line_increment: {}", adjusted_opcode, address_increment, line_increment);
        dbgln("Address is now: {:p}, and line is: {}:{}", m_address, m_source_files[m_file_index].name, m_line);
    }

    append_to_line_info();

    m_basic_block = false;
    m_prologue_end = false;
}

ErrorOr<void> LineProgram::run_program()
{
    reset_registers();

    while (TRY(m_stream.tell()) < m_unit_offset + sizeof(u32) + m_unit_header.length()) {
        auto opcode = TRY(m_stream.read_value<u8>());

        dbgln_if(DWARF_DEBUG, "{:p}: opcode: {}", TRY(m_stream.tell()) - 1, opcode);

        if (opcode == 0) {
            TRY(handle_extended_opcode());
        } else if (opcode >= 1 && opcode <= 12) {
            TRY(handle_standard_opcode(opcode));
        } else {
            handle_special_opcode(opcode);
        }
    }

    return {};
}

LineProgram::DirectoryAndFile LineProgram::get_directory_and_file(size_t file_index) const
{
    VERIFY(file_index < m_source_files.size());
    auto file_entry = m_source_files[file_index];
    VERIFY(file_entry.directory_index < m_source_directories.size());
    auto directory_entry = m_source_directories[file_entry.directory_index];
    return { directory_entry, file_entry.name };
}

bool LineProgram::looks_like_embedded_resource() const
{
    if (source_files().size() == 1)
        return source_files()[0].name.view().contains("serenity_icon_"sv);

    if (source_files().size() == 2 && source_files()[0].name.view() == "."sv)
        return source_files()[1].name.view().contains("serenity_icon_"sv);

    return false;
}

}