繁体   English   中英

Linux内核中的current_thread_info()内联函数?

[英]current_thread_info() inline function in Linux kernel?

我了解到thread_info存储在堆栈的底部。 在查看内核的源代码时,我试图了解如何在linux内核中获取当前的thread_info?
下面的源代码是current_stack_pointer的13位屏蔽。

这是我无法得到的。 我不明白th​​read_info的位置会发生变化。 为什么它是当前的堆栈指针而不是堆栈的开始?

请帮我理解这段代码

/*
 * how to get the current stack pointer in C
 */
register unsigned long current_stack_pointer asm ("sp");

/*
 * how to get the thread information struct from C
 */
static inline struct thread_info *current_thread_info(void) __attribute_const__;

static inline struct thread_info *current_thread_info(void)
{
    return (struct thread_info *)
        (current_stack_pointer & ~(THREAD_SIZE - 1));
}

为什么它是当前的堆栈指针而不是堆栈的开始?

您总是可以从平台特定的堆栈指针寄存器中获取当前堆栈指针,但是您无法轻松找到堆栈的开头 - 它就不存在了。

为此,您可以限制线程堆栈在内存中的位置:堆栈始终在内存中按其大小保持对齐,其大小始终为2的幂。 这样,如果堆栈大小为2^n ,则将较低的n归零可以启动堆栈。

在现代Linux堆栈中,通常为8 KiB,并且始终为8 KiB对齐(其地址的低13位始终为0)。 将当前堆栈指针的低13位归零可以启动堆栈。

这正是表达式current_stack_pointer & ~(THREAD_SIZE - 1)作用:查找当前堆栈的开始。 这并不意味着struct thread_info在内存中移动 - 它不会。 即使堆栈指针发生变化,将较低位置零也会在线程中给出相同的值。 这就是为什么它也用__attribute_const__标记,它扩展为__attribute__((const))并告诉GCC这个函数总是返回相同的值,这样就可以省略对这个函数的多次调用。


PS:当堆栈向下增长时,“当前堆栈的开始”是指最低地址。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM