此文件实现基于 ELF 的系统所使用的两种 TLS 变体[1]。注意,实际上变体 I 还有两个子变体。
必须理解,此处的 TCB(线程控制块)一词有多重含义。官方 ABI 文档仅用它表示 ABI TCB,即由 ABI 定义的一小块数据,通常为一到两个字,参见下方的 AbiTcb 类型。人们也经常用 TCB 指代 libc TCB,后者大小和内容均不受限制,甚至可以完全省略。这里将后者称为 Zig TCB,参见下方的 ZigTcb 类型。
stdmemelfmathassertbuiltinnative_archlinuxpage_size_minVariantcurrent_variantcurrent_tp_offsetcurrent_dtv_offsetAbiTcbZigTcbDtvAreaDescarea_descsetThreadPointergetThreadPointercomputeAreaDescalignForwardalignBackwardalignPtrCastprepareAreamain_thread_area_bufferinitStaticmmap_tls__m68k_read_tpTlsIndex__tls_get_addr___tls_get_addr__tls_get_offset
std.os.linux.tls.___tls_get_addr
函数
fn ___tls_get_addr() callconv(.naked) *anyopaque
std.os.linux.tls.__m68k_read_tp
函数
fn __m68k_read_tp() callconv(.c) ?*anyopaque
std.os.linux.tls.__tls_get_addr
函数
fn __tls_get_addr(ti: *const TlsIndex) callconv(.c) *anyopaque
参数
ti: *const TlsIndex
std.os.linux.tls.__tls_get_offset
函数
fn __tls_get_offset() callconv(.naked) noreturn
std.os.linux.tls.AbiTcb
类型
ELF TLS 应用二进制接口的线程级存储。
std.os.linux.tls.alignBackward
函数
由于线程局部存储尚未建立,因此需要内联。
inline fn alignBackward(addr: usize, alignment: usize) usize
参数
addr: usize
alignment: usize
std.os.linux.tls.alignForward
函数
由于线程局部存储尚未建立,因此需要内联。
inline fn alignForward(addr: usize, alignment: usize) usize
参数
addr: usize
alignment: usize
std.os.linux.tls.alignPtrCast
函数
由于线程局部存储尚未建立,因此需要内联。
inline fn alignPtrCast(comptime T: type, ptr: [*]u8) *T
参数
T: type
ptr: [*]u8
std.os.linux.tls.area_desc
变量
AreaDesc
std.os.linux.tls.AreaDesc
容器
描述进程的 TLS 区域。该区域包含 DTV、两个 TCB 及 TLS 块;
这些部分的确切布局主要取决于 current_variant。
字段
size: usize
alignment: usize
dtv: struct {
/// TLS 区域中的偏移。
offset: usize,
}
abi_tcb: struct {
/// TLS 区域中的偏移。
offset: usize,
}
block: struct {
/// 要复制到 TLS 块的初始数据。注意,它可能小于
/// `size`;此时 TLS 块中剩余数据直接保持未初始化。
init: []const u8,
/// TLS 区域中的偏移。
offset: usize,
/// 这是 TLS 块的有效大小,可能大于 `init.len`。
size: usize,
}
gdt_entry_number: usize仅用于 32 位 x86 架构(不包括 x86_64 或 x32)。
std.os.linux.tls.assert
别名
别名目标 std.debug.assert
std.os.linux.tls.builtin
常量
std.os.linux.tls.computeAreaDesc
函数
fn computeAreaDesc(phdrs: []elf.ElfN.Phdr) void
参数
std.os.linux.tls.current_dtv_offset
常量
通常仅由修改后的变体 I 使用。
std.os.linux.tls.current_tp_offset
常量
修改后的变体 I 的偏移值。
std.os.linux.tls.current_variant
常量
Variant
std.os.linux.tls.Dtv
容器
ELF TLS ABI 规定的动态线程向量。通常每个动态加载模块对应一个块指针, 但由于这里只支持静态 TLS,因此仅需一个块指针。
字段
len: usize = 1
tls_block: [*]u8
std.os.linux.tls.elf
别名
别名目标 std.elf
std.os.linux.tls.getThreadPointer
函数
pub fn getThreadPointer() usize
std.os.linux.tls.initStatic
函数
计算静态 TLS 区域布局、分配该区域、初始化全部字段,并向 TP 寄存器写入架构专属值。
pub fn initStatic(phdrs: []elf.ElfN.Phdr) void
参数
std.os.linux.tls.linux
别名
别名目标 std.os.linux
std.os.linux.tls.main_thread_area_buffer
变量
此处选择该大小的主要原因是,对于多数程序,它大于线程局部变量的总量。
像这样将此分配放入 ELF,相当于将下方的 mmap 调用
移入内核,从而避免系统调用开销。
[0x1000]u8
std.os.linux.tls.math
别名
别名目标 std.math
std.os.linux.tls.mem
别名
别名目标 std.mem
std.os.linux.tls.mmap_tls
函数
inline fn mmap_tls(length: usize) usize
参数
length: usize
std.os.linux.tls.native_arch
常量
std.os.linux.tls.page_size_min
别名
std.os.linux.tls.prepareArea
函数
初始化静态 TLS 区域的全部字段,并返回计算出的架构专属 TP 寄存器值。
pub fn prepareArea(area: []u8) usize
参数
area: []u8
std.os.linux.tls.setThreadPointer
函数
pub fn setThreadPointer(addr: usize) void
参数
addr: usize
std.os.linux.tls.std
别名
别名目标 std
std.os.linux.tls.TlsIndex
类型
std.os.linux.tls.Variant
容器
表示 ELF TLS 变体。
所有变体中,TP 和 TLS 块均须按 PT.TLS ELF 程序头中的
p_align 值对齐。其他内容采用自然对齐。
DTV 的位置实际上无关紧要。为简单起见,将其放在 TLS 区域中, 但 ABI 实际并不要求它必须位于此处。
字段
I_original最初的变体 I:
| DTV | Zig TCB | ABI TCB | TLS 块 |
----------------^-----------------------
-- TP 寄存器指向此处。
此变体的布局要求分别对齐 TP 和 TLS 块。
ABI TCB 中的第一个字指向 DTV。对某些架构,可能还有 含义未指定的第二个字。
I_modified修改后的变体 I:
| DTV | Zig TCB | ABI TCB | TLS Blocks |
------------------------------^-------------
-- TP 寄存器指向此处,位于 TLS 块*内部*。
TLS 块起始位置到 TP 寄存器的偏移为 current_tp_offset。
此值可以为零,此时 TP 寄存器指向 TLS 块的起始位置。
ABI TCB 中第一个也是唯一的机器字指向 DTV。
II变体 II:
| TLS Blocks | ABI TCB | Zig TCB | DTV |
-------------^--------------------------
-- TP 寄存器指向此处。
ABI TCB 中的第一个(也是唯一一个)字指向 ABI TCB 本身。
std.os.linux.tls.ZigTcb
容器
供 Zig 使用的逐线程存储。目前未使用。
字段
dummy: usize
源码
std/os/linux/tls.zig
//! 此文件实现基于 ELF 的系统所使用的两种 TLS 变体[1]。注意,实际上变体 I 还有两个子变体。
//!
//! 必须理解,此处的 TCB(线程控制块)一词有多重含义。官方 ABI 文档仅用它表示 ABI TCB,即由 ABI 定义的一小块数据,通常为一到两个字,参见下方的 `AbiTcb` 类型。人们也经常用 TCB 指代 libc TCB,后者大小和内容均不受限制,甚至可以完全省略。这里将后者称为 Zig TCB,参见下方的 `ZigTcb` 类型。
//!
//! [1] https://www.akkadia.org/drepper/tls.pdf
//!
//!
//!
//!
//!
const std = @import("std");
const mem = std.mem;
const elf = std.elf;
const math = std.math;
const assert = std.debug.assert;
const builtin = @import("builtin");
const native_arch = builtin.cpu.arch;
const linux = std.os.linux;
const page_size_min = std.heap.page_size_min;
/// 表示 ELF TLS 变体。
///
/// 所有变体中,TP 和 TLS 块均须按 `PT.TLS` ELF 程序头中的
/// `p_align` 值对齐。其他内容采用自然对齐。
///
/// DTV 的位置实际上无关紧要。为简单起见,将其放在 TLS 区域中,
/// 但 ABI 实际并不要求它必须位于此处。
const Variant = enum {
/// 最初的变体 I:
///
/// ----------------------------------------
/// | DTV | Zig TCB | ABI TCB | TLS 块 |
/// ----------------^-----------------------
/// `-- TP 寄存器指向此处。
///
/// 此变体的布局要求分别对齐 TP 和 TLS
/// 块。
///
/// ABI TCB 中的第一个字指向 DTV。对某些架构,可能还有
/// 含义未指定的第二个字。
I_original,
/// 修改后的变体 I:
///
/// --------------------------------------------
/// | DTV | Zig TCB | ABI TCB | TLS Blocks |
/// ------------------------------^-------------
/// `-- TP 寄存器指向此处,位于 TLS 块*内部*。
///
/// TLS 块起始位置到 TP 寄存器的偏移为 `current_tp_offset`。
/// 此值可以为零,此时 TP 寄存器指向 TLS 块的起始位置。
///
/// ABI TCB 中第一个也是唯一的机器字指向 DTV。
I_modified,
/// 变体 II:
///
/// ----------------------------------------
/// | TLS Blocks | ABI TCB | Zig TCB | DTV |
/// -------------^--------------------------
/// `-- TP 寄存器指向此处。
///
/// ABI TCB 中的第一个(也是唯一一个)字指向 ABI TCB 本身。
II,
};
const current_variant: Variant = switch (native_arch) {
.aarch64,
.aarch64_be,
.alpha,
.arc,
.arceb,
.arm,
.armeb,
.csky,
.hppa,
.microblaze,
.microblazeel,
.sh,
.sheb,
.thumb,
.thumbeb,
.xtensa,
.xtensaeb,
=> .I_original,
.loongarch32,
.loongarch64,
.m68k,
.mips,
.mipsel,
.mips64,
.mips64el,
.or1k,
.powerpc,
.powerpcle,
.powerpc64,
.powerpc64le,
.riscv32,
.riscv64,
=> .I_modified,
.hexagon,
.s390x,
.sparc,
.sparc64,
.x86,
.x86_64,
=> .II,
else => @compileError("undefined TLS variant for this architecture"),
};
/// 修改后的变体 I 的偏移值。
const current_tp_offset = switch (native_arch) {
.m68k,
.mips,
.mipsel,
.mips64,
.mips64el,
.powerpc,
.powerpcle,
.powerpc64,
.powerpc64le,
=> 0x7000,
else => 0,
};
/// 通常仅由修改后的变体 I 使用。
const current_dtv_offset = switch (native_arch) {
.m68k,
.mips,
.mipsel,
.mips64,
.mips64el,
.powerpc,
.powerpcle,
.powerpc64,
.powerpc64le,
=> 0x8000,
.riscv32,
.riscv64,
=> 0x800,
else => 0,
};
/// ELF TLS 应用二进制接口的线程级存储。
const AbiTcb = switch (current_variant) {
.I_original => extern struct {
/// 此值以 `current_dtv_offset` 为偏移。
dtv: usize,
_reserved: ?*anyopaque,
},
.I_modified => extern struct {
/// 此值以 `current_dtv_offset` 为偏移。
dtv: usize,
},
.II => extern struct {
/// 这是自引用的。
self: *AbiTcb,
},
};
/// 供 Zig 使用的逐线程存储。目前未使用。
const ZigTcb = struct {
dummy: usize,
};
/// ELF TLS ABI 规定的动态线程向量。通常每个动态加载模块对应一个块指针,
/// 但由于这里只支持静态 TLS,因此仅需一个块指针。
const Dtv = extern struct {
len: usize = 1,
tls_block: [*]u8,
};
/// 描述进程的 TLS 区域。该区域包含 DTV、两个 TCB 及 TLS 块;
/// 这些部分的确切布局主要取决于 `current_variant`。
const AreaDesc = struct {
size: usize,
alignment: usize,
dtv: struct {
/// TLS 区域中的偏移。
offset: usize,
},
abi_tcb: struct {
/// TLS 区域中的偏移。
offset: usize,
},
block: struct {
/// 要复制到 TLS 块的初始数据。注意,它可能小于
/// `size`;此时 TLS 块中剩余数据直接保持未初始化。
init: []const u8,
/// TLS 区域中的偏移。
offset: usize,
/// 这是 TLS 块的有效大小,可能大于 `init.len`。
size: usize,
},
/// 仅用于 32 位 x86 架构(不包括 x86_64 或 x32)。
gdt_entry_number: usize,
};
pub var area_desc: AreaDesc = undefined;
pub fn setThreadPointer(addr: usize) void {
@setRuntimeSafety(false);
@disableInstrumentation();
switch (native_arch) {
.x86 => {
var user_desc: linux.user_desc = .{
.entry_number = area_desc.gdt_entry_number,
.base_addr = addr,
.limit = 0xfffff,
.flags = .{
.seg_32bit = 1,
.contents = 0, // 数据
.read_exec_only = 0,
.limit_in_pages = 1,
.seg_not_present = 0,
.useable = 1,
},
};
const rc = @call(.always_inline, linux.syscall1, .{ .set_thread_area, @intFromPtr(&user_desc) });
assert(rc == 0);
const gdt_entry_number = user_desc.entry_number;
// 必须跟踪本槽位,因为 clone() 也需要它
area_desc.gdt_entry_number = gdt_entry_number;
// 更新 %gs 选择子
asm volatile ("movl %[gs_val], %%gs"
:
: [gs_val] "r" (gdt_entry_number << 3 | 3),
);
},
.x86_64 => {
const rc = @call(.always_inline, linux.syscall2, .{ .arch_prctl, linux.ARCH.SET_FS, addr });
assert(rc == 0);
},
.aarch64, .aarch64_be => {
asm volatile (
\\ msr tpidr_el0, %[addr]
:
: [addr] "r" (addr),
);
},
.alpha => {
asm volatile (
\\ wruniq
:
: [addr] "{$16}" (addr),
);
},
.arc, .arceb => {
// 看来既需要设置 r25(TP),*又*需要通知内核……
asm volatile (
\\ mov r25, %[addr]
:
: [addr] "r" (addr),
);
const rc = @call(.always_inline, linux.syscall1, .{ .arc_settls, addr });
assert(rc == 0);
},
.arm, .armeb, .thumb, .thumbeb => {
const rc = @call(.always_inline, linux.syscall1, .{ .set_tls, addr });
assert(rc == 0);
},
.m68k => {
const rc = @call(.always_inline, linux.syscall1, .{ .set_thread_area, addr });
assert(rc == 0);
},
.hexagon => {
asm volatile (
\\ ugp = %[addr]
:
: [addr] "r" (addr),
);
},
.hppa => {
asm volatile (
\\ ble 0xe0(%%sr2, %%r0)
\\ nop
:
: [addr] "{r26}" (addr),
: .{ .r31 = true });
},
.loongarch32, .loongarch64 => {
asm volatile (
\\ move $tp, %[addr]
:
: [addr] "r" (addr),
);
},
.riscv32, .riscv64 => {
asm volatile (
\\ mv tp, %[addr]
:
: [addr] "r" (addr),
);
},
.csky, .mips, .mipsel, .mips64, .mips64el => {
const rc = @call(.always_inline, linux.syscall1, .{ .set_thread_area, addr });
assert(rc == 0);
},
.microblaze, .microblazeel => {
asm volatile (
\\ ori r21, %[addr], 0
:
: [addr] "r" (addr),
);
},
.or1k => {
asm volatile (
\\ l.ori r10, %[addr], 0
:
: [addr] "r" (addr),
);
},
.powerpc, .powerpcle => {
asm volatile (
\\ mr 2, %[addr]
:
: [addr] "r" (addr),
);
},
.powerpc64, .powerpc64le => {
asm volatile (
\\ mr 13, %[addr]
:
: [addr] "r" (addr),
);
},
.s390x => {
asm volatile (
\\ lgr %%r0, %[addr]
\\ sar %%a1, %%r0
\\ srlg %%r0, %%r0, 32
\\ sar %%a0, %%r0
:
: [addr] "r" (addr),
: .{ .r0 = true });
},
.sh, .sheb => {
asm volatile (
\\ ldc %[addr], gbr
:
: [addr] "r" (addr),
);
},
.sparc, .sparc64 => {
asm volatile (
\\ mov %[addr], %%g7
:
: [addr] "r" (addr),
);
},
.xtensa, .xtensaeb => {
asm volatile (
\\ wur %[addr], threadptr
:
: [addr] "a" (addr),
);
},
else => @compileError("Unsupported architecture"),
}
}
pub fn getThreadPointer() usize {
@setRuntimeSafety(false);
@disableInstrumentation();
return switch (native_arch) {
.aarch64, .aarch64_be => asm (
\\ mrs %[ret], tpidr_el0
: [ret] "=r" (-> usize),
),
.alpha => asm (
\\ rduniq
: [ret] "={$0}" (-> usize),
),
.arc, .arceb => asm (
\\ mov %[ret], r25
: [ret] "=r" (-> usize),
),
.arm, .armeb, .thumb, .thumbeb => asm (
\\ mrc p15, 0, %[ret], c13, c0, 3
: [ret] "=r" (-> usize),
),
.csky => asm (
\\ mov %[ret], r31
: [ret] "=r" (-> usize),
),
.hexagon => asm (
\\ %[ret] = ugp
: [ret] "=r" (-> usize),
),
.hppa => asm (
\\ mfctl %%cr27, %[ret]
: [ret] "=r" (-> usize),
),
.loongarch32, .loongarch64 => asm (
\\ move %[ret], $tp
: [ret] "=r" (-> usize),
),
.m68k => linux.syscall0(.get_thread_area),
.mips, .mipsel, .mips64, .mips64el => asm (
\\ rdhwr %[ret], $29
: [ret] "=r" (-> usize),
),
.microblaze, .microblazeel => asm (
\\ ori %[ret], r21, 0
: [ret] "=r" (-> usize),
),
.or1k => asm (
\\ l.ori %[ret], r10, 0
: [ret] "=r" (-> usize),
),
.riscv32, .riscv64 => asm (
\\ mv %[ret], tp
: [ret] "=r" (-> usize),
),
.powerpc, .powerpcle => asm (
\\ mr %[ret], 2
: [ret] "=r" (-> usize),
),
.powerpc64, .powerpc64le => asm (
\\ mr %[ret], 13
: [ret] "=r" (-> usize),
),
.s390x => asm (
\\ ear %[ret], %%a0
\\ sllg %[ret], %[ret], 32
\\ ear %[ret], %%a1
: [ret] "=r" (-> usize),
),
.sh, .sheb => asm (
\\ stc gbr, %[ret]
: [ret] "=r" (-> usize),
),
.sparc, .sparc64 => asm (
\\ mov %%g7, %[ret]
: [ret] "=r" (-> usize),
),
.x86 => asm (
\\ movl %%gs:0, %[ret]
: [ret] "=r" (-> usize),
),
.x86_64 => switch (@sizeOf(usize)) {
8 => asm (
\\ movq %%fs:0, %[ret]
: [ret] "=r" (-> usize),
),
// 在 x32 上,usize 为 32 位。
4 => asm (
\\ movl %%fs:0, %[ret]
: [ret] "=r" (-> usize),
),
else => comptime unreachable,
},
.xtensa, .xtensaeb => asm (
\\ rur %[ret], threadptr
: [ret] "=r" (-> usize),
),
else => @compileError("Unsupported architecture"),
};
}
fn computeAreaDesc(phdrs: []elf.ElfN.Phdr) void {
@setRuntimeSafety(false);
@disableInstrumentation();
var tls_phdr: ?*elf.ElfN.Phdr = null;
var img_base: usize = 0;
for (phdrs) |*phdr| {
switch (phdr.type) {
.PHDR => img_base = @intFromPtr(phdrs.ptr) - phdr.vaddr,
.TLS => tls_phdr = phdr,
else => {},
}
}
var align_factor: usize = undefined;
var block_init: []const u8 = undefined;
var block_size: usize = undefined;
if (tls_phdr) |phdr| {
align_factor = @max(phdr.@"align", 1);
// 实际内存大小由 `memsz` 表示;存储在 `PT.TLS` 段中的数据长度为
// `filesz`,可能小于前者。
block_init = @as([*]u8, @ptrFromInt(img_base + phdr.vaddr))[0..phdr.filesz];
block_size = phdr.memsz;
} else {
align_factor = @alignOf(usize);
block_init = &[_]u8{};
block_size = 0;
}
// 已分配 TLS 区域内的偏移。
var dtv_offset: usize = undefined;
var abi_tcb_offset: usize = undefined;
var block_offset: usize = undefined;
// 计算 ABI 专属数据及自身 `ZigTcb` 结构体的总大小。
// 此处计算的所有偏移均假定基址正确对齐。
const area_size = switch (current_variant) {
.I_original => blk: {
var l: usize = 0;
dtv_offset = l;
l += @sizeOf(Dtv);
// 在此添加填充,使 TP(`abi_tcb_offset`)按 `align_factor` 对齐,
// 并且只需从 TP 减去 `@sizeOf(ZigTcb)`,
// 即可找到 `ZigTcb` 结构。
const delta = (l + @sizeOf(ZigTcb)) & (align_factor - 1);
if (delta > 0)
l += align_factor - delta;
l += @sizeOf(ZigTcb);
abi_tcb_offset = l;
l += alignForward(@sizeOf(AbiTcb), align_factor);
block_offset = l;
l += block_size;
break :blk l;
},
.I_modified => blk: {
var l: usize = 0;
dtv_offset = l;
l += @sizeOf(Dtv);
// 在此变体中,TLS 块必须紧接在 ABI TCB 末尾之后开始,TP 指向 TLS 块的起始位置。
// 添加填充,使 TP(`abi_tcb_offset`)按 `align_factor` 对齐,并且能够找到 `ZigTcb` 结构体,方法是从 TP 减去 `@sizeOf(AbiTcb) + @sizeOf(ZigTcb)`。
//
//
const delta = (l + @sizeOf(ZigTcb) + @sizeOf(AbiTcb)) & (align_factor - 1);
if (delta > 0)
l += align_factor - delta;
l += @sizeOf(ZigTcb);
abi_tcb_offset = l;
l += @sizeOf(AbiTcb);
block_offset = l;
l += block_size;
break :blk l;
},
.II => blk: {
var l: usize = 0;
block_offset = l;
l += alignForward(block_size, align_factor);
// TP 与 `align_factor` 对齐。
abi_tcb_offset = l;
l += @sizeOf(AbiTcb);
// `ZigTcb` 结构紧随 `AbiTcb` 之后,中间没有填充,
// 因此很容易找到。
l += @sizeOf(ZigTcb);
// DTV 放置位置并不重要,因此使用其自然对齐。
l = alignForward(l, @alignOf(Dtv));
dtv_offset = l;
l += @sizeOf(Dtv);
break :blk l;
},
};
area_desc = .{
.size = area_size,
.alignment = align_factor,
.dtv = .{
.offset = dtv_offset,
},
.abi_tcb = .{
.offset = abi_tcb_offset,
},
.block = .{
.init = block_init,
.offset = block_offset,
.size = block_size,
},
.gdt_entry_number = @as(usize, @bitCast(@as(isize, -1))),
};
}
/// 由于线程局部存储尚未建立,因此需要内联。
inline fn alignForward(addr: usize, alignment: usize) usize {
return alignBackward(addr + (alignment - 1), alignment);
}
/// 由于线程局部存储尚未建立,因此需要内联。
inline fn alignBackward(addr: usize, alignment: usize) usize {
return addr & ~(alignment - 1);
}
/// 由于线程局部存储尚未建立,因此需要内联。
inline fn alignPtrCast(comptime T: type, ptr: [*]u8) *T {
return @ptrCast(@alignCast(ptr));
}
/// 初始化静态 TLS 区域的全部字段,并返回计算出的架构专属 TP 寄存器值。
///
pub fn prepareArea(area: []u8) usize {
@setRuntimeSafety(false);
@disableInstrumentation();
// 清空即将使用的区域,以确保安全。
@memset(area, 0);
// 准备 ABI TCB。
const abi_tcb = alignPtrCast(AbiTcb, area.ptr + area_desc.abi_tcb.offset);
switch (current_variant) {
.I_original, .I_modified => abi_tcb.dtv = @intFromPtr(area.ptr + area_desc.dtv.offset),
.II => abi_tcb.self = abi_tcb,
}
// 准备 DTV。
const dtv = alignPtrCast(Dtv, area.ptr + area_desc.dtv.offset);
dtv.len = 1;
dtv.tls_block = area.ptr + current_dtv_offset + area_desc.block.offset;
// 复制初始数据。
@memcpy(area[area_desc.block.offset..][0..area_desc.block.init.len], area_desc.block.init);
// 返回 TP 寄存器的修正值(若需要)。此处溢出没有问题,
// 因为涉及 TP 的指针运算采用回绕语义。
return @intFromPtr(area.ptr) +% switch (current_variant) {
.I_original, .II => area_desc.abi_tcb.offset,
.I_modified => area_desc.block.offset +% current_tp_offset,
};
}
/// 此处选择该大小的主要原因是,对于多数程序,它大于线程局部变量的总量。
/// 像这样将此分配放入 ELF,相当于将下方的 `mmap` 调用
/// 移入内核,从而避免系统调用开销。
///
var main_thread_area_buffer: [0x1000]u8 align(page_size_min) = undefined;
/// 计算静态 TLS 区域布局、分配该区域、初始化全部字段,并向 TP 寄存器写入架构专属值。
///
pub fn initStatic(phdrs: []elf.ElfN.Phdr) void {
@setRuntimeSafety(false);
@disableInstrumentation();
computeAreaDesc(phdrs);
const area = blk: {
// TLS 数据很小时的常见情况使用快速路径,避免分配,
// 使用本地缓冲区。
if (area_desc.alignment <= page_size_min and area_desc.size <= main_thread_area_buffer.len) {
break :blk main_thread_area_buffer[0..area_desc.size];
}
const begin_addr = mmap_tls(area_desc.size + area_desc.alignment - 1);
if (@call(.always_inline, linux.errno, .{begin_addr}) != .SUCCESS) @trap();
const area_ptr: [*]align(page_size_min) u8 = @ptrFromInt(begin_addr);
// 确保切片正确对齐。
const begin_aligned_addr = alignForward(begin_addr, area_desc.alignment);
const start = begin_aligned_addr - begin_addr;
break :blk area_ptr[start..][0..area_desc.size];
};
const tp_value = prepareArea(area);
setThreadPointer(tp_value);
}
inline fn mmap_tls(length: usize) usize {
const prot: linux.PROT = .{ .READ = true, .WRITE = true };
const flags: linux.MAP = .{ .TYPE = .PRIVATE, .ANONYMOUS = true };
if (@hasField(linux.SYS, "mmap2")) {
return @call(.always_inline, linux.syscall6, .{
.mmap2,
0,
length,
@as(u32, @bitCast(prot)),
@as(u32, @bitCast(flags)),
@as(usize, @bitCast(@as(isize, -1))),
0,
});
} else {
// s390x 的 mmap() 系统调用早于 Linux 支持 5 个及以上参数的系统调用,因此它只接受一个指向参数数组的指针。
//
return if (native_arch == .s390x) @call(.always_inline, linux.syscall1, .{
.mmap,
@intFromPtr(&[_]usize{
0,
length,
@as(u32, @bitCast(prot)),
@as(u32, @bitCast(flags)),
@as(usize, @bitCast(@as(isize, -1))),
0,
}),
}) else @call(.always_inline, linux.syscall6, .{
.mmap,
0,
length,
@as(u32, @bitCast(prot)),
@as(u32, @bitCast(flags)),
@as(usize, @bitCast(@as(isize, -1))),
0,
});
}
}
comptime {
assert(!builtin.link_libc); // 否则应由 libc 控制 TLS
if (builtin.output_mode == .Exe and builtin.link_mode == .static) {
// 这是未链接 libc 的静态可执行文件,因此需要由我们提供 GD 和 LD 模型的 TLS 访问
// 函数。实际使用此函数的可能性很低,因为
// 链接器应能将所有 TLS 访问松弛为 LE 模型,从而
// 消除对此函数的所有调用,但并不保证如此。
const Fns = struct {
fn __m68k_read_tp() callconv(.c) ?*anyopaque {
comptime assert(native_arch == .m68k);
return @ptrFromInt(getThreadPointer());
}
const TlsIndex = switch (native_arch) {
.x86_64 => extern struct { module: u64, offset: u64 }, // 即使是 x32……
else => extern struct { module: usize, offset: usize }, // ……但 MIPS N32 除外!
};
fn __tls_get_addr(ti: *const TlsIndex) callconv(.c) *anyopaque {
comptime assert(native_arch != .s390x);
assert(ti.module == 1); // 可执行文件的模块 ID 始终为 1
const tp = getThreadPointer();
const block = switch (current_variant) {
.I_original => tp -% area_desc.abi_tcb.offset +% area_desc.block.offset,
.I_modified => tp -% current_tp_offset,
// `.I_original` 方法也适用于 `.II`,但还有
// 另一种少一次运算的策略:
.II => tp -% area_desc.abi_tcb.offset,
};
return @ptrFromInt(block +% current_dtv_offset +% @as(usize, @intCast(ti.offset)));
}
fn ___tls_get_addr() callconv(.naked) *anyopaque {
comptime assert(native_arch == .x86);
// 在 eax 中接收 `TlsIndex` 指针。
comptime assert(@sizeOf(AbiTcb) + @sizeOf(ZigTcb) + @offsetOf(Dtv, "tls_block") == 12);
asm volatile (
\\ mov 4(%%eax), %%eax
\\ add %%gs:12, %%eax
\\ ret
);
}
fn __tls_get_offset() callconv(.naked) noreturn {
comptime assert(native_arch == .s390x);
// 通过 r12 接收模块的 GOT 指针,通过 r2 接收 GOT 偏移。
asm volatile (
\\ la %%r1, 0(%%r12, %%r2)
\\ lg %%r2, 8(%%r1)
\\ lgrl %%r0, %[abi_tcb_offset]
\\ sgr %%r2, %%r0
\\ br %%r14
:
: [abi_tcb_offset] "s" (&area_desc.abi_tcb.offset),
);
}
};
if (native_arch == .s390x) {
@export(&Fns.__tls_get_offset, .{ .name = "__tls_get_offset" });
} else {
@export(&Fns.__tls_get_addr, .{ .name = "__tls_get_addr" });
if (native_arch == .m68k) {
@export(&Fns.__m68k_read_tp, .{ .name = "__m68k_read_tp" });
}
if (native_arch == .x86) {
@export(&Fns.___tls_get_addr, .{ .name = "___tls_get_addr" });
}
}
}
}