博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linux源码解析-内核栈与thread_info结构详解
阅读量:4212 次
发布时间:2019-05-26

本文共 1826 字,大约阅读时间需要 6 分钟。

环境:linux2.6.34

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

3.内核栈的大小?

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

alloc_thread_info函数通过调用
__get_free_pages函数分配
2个页的内存(8192字节)
你可能感兴趣的文章
【一天一道LeetCode】#30. Substring with Concatenation of All Words
查看>>
【一天一道LeetCode】#60. Permutation Sequence.
查看>>
【一天一道LeetCode】#113. Path Sum II
查看>>
【一天一道LeetCode】#114. Flatten Binary Tree to Linked List
查看>>
【unix网络编程第三版】阅读笔记(二):套接字编程简介
查看>>
【一天一道LeetCode】#115. Distinct Subsequences
查看>>
【一天一道LeetCode】#116. Populating Next Right Pointers in Each Node
查看>>
【一天一道LeetCode】#117. Populating Next Right Pointers in Each Node II
查看>>
【一天一道LeetCode】#118. Pascal's Triangle
查看>>
同步与异步的区别
查看>>
IT行业--简历模板及就业秘籍
查看>>
JNI简介及实例
查看>>
JAVA实现文件树
查看>>
linux -8 Linux磁盘与文件系统的管理
查看>>
linux 9 -文件系统的压缩与打包 -dump
查看>>
PHP在变量前面加&是什么意思?
查看>>
ebay api - GetUserDisputes 函数
查看>>
ebay api GetMyMessages 函数
查看>>
php加速器 - zendopcache
查看>>
手动12 - 安装php加速器 Zend OPcache
查看>>