TPDE
Loading...
Searching...
No Matches
FunctionWriterX64.hpp
1// SPDX-FileCopyrightText: 2025 Contributors to TPDE <https://tpde.org>
2// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3#pragma once
4
5#include "tpde/FunctionWriter.hpp"
6#include "tpde/base.hpp"
7#include <fadec-enc2.h>
8
9namespace tpde::x64 {
10
11/// Helper class to write function text for X64.
12class FunctionWriterX64 : public FunctionWriter<FunctionWriterX64> {
13 friend class FunctionWriter<FunctionWriterX64>;
14
15 static const TargetCIEInfo CIEInfo;
16
17 // LEA tmp, [rip+table]; MOVSX idx, [tmp+4*idx]; ADD tmp, idx; JMP tmp
18 // NB: MOVSX can be 5 bytes in case tmp is r13.
19 static constexpr u32 JumpTableCodeSize = 18;
20
21public:
22 FunctionWriterX64() : FunctionWriter(CIEInfo) {}
23
24 void align(size_t align) {
25 u32 old_off = offset();
26 FunctionWriter::align(align);
27 // Pad text section with NOPs.
28 if (u32 cur_off = offset(); cur_off > old_off) {
29 fe64_NOP(cur_ptr() - (cur_off - old_off), cur_off - old_off);
30 }
31 }
32
33 JumpTable &create_jump_table(u32 size, Reg idx, Reg tmp) {
34 JumpTable &jt = alloc_jump_table(size, idx, tmp);
35 ensure_space(JumpTableCodeSize);
36 cur_ptr() += JumpTableCodeSize;
37 return jt;
38 }
39
40private:
41 void handle_fixups();
42};
43
44} // namespace tpde::x64
u8 *& cur_ptr()
Modifiable pointer to current writing position of the section.
JumpTable & alloc_jump_table(u32 size, Reg idx, Reg tmp)
Allocate a jump table for the current location.
size_t offset() const
Get the current offset into the section.