设为首页 加入收藏

TOP

Linux源码解析-内核栈与thread_info结构详解
2019-09-01 23:09:48 】 浏览:24
Tags:Linux 源码 解析 内核 thread_info 结构 详解

1.什么是进程的内核栈?

在内核态(比如应用进程执行系统调用)时,进程运行需要自己的堆栈信息(不是原用户空间中的栈),而是使用内核空间中的栈,这个栈就是进程的内核栈

2.进程的内核栈在计算机中是如何描述的?

linux中进程使用task_struct数据结构描述,其中有一个stack指针

struct task_struct
{
    // ...
    void *stack;    //  指向内核栈的指针
    // ...
};

task_struct数据结构中的stack成员指向thread_union结构(Linux内核通过thread_union联合体来表示进程的内核栈)

union thread_union {
    struct thread_info thread_info;
    unsigned long stack[THREAD_SIZE/sizeof(long)];  
};

struct thread_info是记录部分进程信息的结构体,其中包括了进程上下文信息:

struct thread_info {
    struct pcb_struct   pcb;        /* palcode state */
 
    struct task_struct  *task;      /* main task structure */  /*这里很重要,task指针指向的是所创建的进程的struct task_struct
    unsigned int        flags;      /* low level flags */
    unsigned int        ieee_state; /* see fpu.h */
 
    struct exec_domain  *exec_domain;   /* execution domain */  /*表了当前进程是属于哪一种规范的可执行程序,
                                                                        //不同的系统产生的可执行文件的差异存放在变量exec_domain中
    mm_segment_t        addr_limit; /* thread address space */
    unsigned        cpu;        /* current CPU */
    int         preempt_count; /* 0 => preemptable, <0 => BUG */
 
    int bpt_nsaved;
    unsigned long bpt_addr[2];      /* breakpoint handling  */
    unsigned int bpt_insn[2];
 
    struct restart_block    restart_block;
};

从用户态刚切换到内核态以后,进程的内核栈总是空的。因此,esp寄存器指向这个栈的顶端,一旦数据写入堆栈,esp的值就递减

3.thread_info的作用是?

这个结构体保存了进程描述符中中频繁访问和需要快速访问的字段,内核依赖于该数据结构来获得当前进程的描述符(为了获取当前CPU上运行进程的task_struct结构,内核提供了current宏。

    #define get_current() (current_thread_info()->task)
    #define current get_current()

内核还需要存储每个进程的PCB信息, linux内核是支持不同体系的的, 但是不同的体系结构可能进程需要存储的信息不尽相同,

这就需要我们实现一种通用的方式, 我们将体系结构相关的部分和无关的部门进行分离,用一种通用的方式来描述进程, 这就是struct task_struct, 而thread_info

就保存了特定体系结构的汇编代码段需要访问的那部分进程的数据,我们在thread_info中嵌入指向task_struct的指针, 则我们可以很方便的通过thread_info来查找task_struct

4.内核栈的大小?

进程通过alloc_thread_info函数分配它的内核栈,通过free_thread_info函数释放所分配的内核栈,查看源码

alloc_thread_info函数通过调用__get_free_pages函数分配2个页的内存(8192字节)

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Linux进程描述符task_struct结构.. 下一篇Linux进程ID号--Linux进程的管理..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目