Linux 内核常见的宏(1):offsetof 和 container_of分析

简介: Linux 内核常见的宏(1):offsetof 和 container_of分析

hello, 大家好,今天和大家一起学习 Linux 内核中常见的两个宏 offsetof 和 container_of。对于初学者,很容易弄懵逼。


offsetof


定义:include/linux/stddef.h ;功能:给定一个TYPE结构和其成员,获取其成员相对于首地址的偏移。


#define offsetof(TYPE, MEMBER)  ((size_t) &((TYPE *)0)->MEMBER)


分析: ((size_t) &((TYPE *)0)->MEMBER),假设TYPE 数据类型如下:


typedef struct student {
    char name[32];
    int age;
};


第一步:我们先看最里层((TYPE*)0)。实际上是将0地址强转为TYPE结构的指针。指向一个TYPE类型的结构体变量,这里就是 student 类型。


第二步:((TYPE*)0)->MEMBER。(TYPE*)0 表示一个TYPE类型的结构体指针。通过指针来访问这个结构体变量的MEMBER元素。student->age


第三步:&((TYPE*)0)->MEMBER 等效于 &(((TYPE*)0)->MEMBER) - &((TYPE *)0)


# 这里取巧 利用了 0地址的结构体指针变量。
&((TYPE*)0)->MEMBER =  &(((TYPE*)0)->MEMBER) - &((TYPE *)0)


代入student,去理解。offsetof(student, age),实际上就是获取相对于student首地址的偏移。


实验验证:


#include <stdio.h>
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
typedef struct _student1 {
    char name[32];
    int age;
} student1_t;
typedef struct _student2 {
    char name[32];
    int age;
    float score;                     
} student2_t;
int main()
{
    size_t addr = 0;
    addr = offsetof(student1_t, age);
    printf("student1_t addr = %d\n", addr);
    addr = offsetof(student2_t, score);
    printf("student2_t addr = %d\n", addr);
    return 0;
}


可以看到,addr输出的值分别对应age 和 score 相对于其结构体首地址的偏移。

思考一个问题,这样做的好处是什么呢?


container_of 宏


在看另外一个宏container_of 宏。


定义:include/linux/kernel.h


/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr:             the pointer to the member.
 * @type:           the type of the container struct this is embedded in.
 * @member:     the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member) ({        \ 
    const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
    (type *)( (char *)__mptr - offsetof(type,member) );})


分析containr_of 宏,我们还是以student结构体为例代入:


第一步:先看第一段。


const typeof( ((type *)0)->member ) *__mptr = (ptr); 
 // 等价于
 const typeof(A) *__mptr = (ptr);


继续拆开:A =  ((type *)0)->member,和上文offsetof 分析一样。这里指的是student->age.然后作为参数传给typeof。


然后typeof(A) *__mptr = ptr; 等价于 A *__mptr = ptr;


注:typeof() 是gcc的扩展宏,给定一个参数或者变量名,能够自动推导数据类型。此时ptr 就指向 student->age地址处。


第二步:再看第二段。


(type *)( (char *)__mptr - offsetof(type,member) );
#等价于
(type *) (&A - offset)


根据 typeof 推算出 member 所在地址,然后减去 member相对于 type 的偏移,得到结构体变量的首地址。


验证:


#include <stdio.h>
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr:        the pointer to the member.
 * @type:       the type of the container struct this is embedded in.
 * @member:     the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member) ({                      \
    const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
    (type *)( (char *)__mptr - offsetof(type,member) );})
typedef struct _student1 {
    char name[32];
    int age;
} student1_t;
typedef struct _student2 {
    char name[32];
    int age;
    float score;
} student2_t;
int main()
{
    student1_t s1[2] = {
    {
        .name = "s1",
        .age = 18,
    },
    {
        .name = "s2",
        .age = 20,
    },
    };
    student1_t *ptr = NULL;
    ptr = container_of(&s1[1].age, student1_t, age);
    printf("s1 addr = %p \n", &s1[0]);
    printf("ptr addr = %p \n", ptr);
    printf("s2 addr = %p, s2.age = %d \n", &s1[1], s1[1].age);
    printf("ptr addr = %p, ptr.age = %d \n", ptr, ptr->age);
    return 0;
}


可以看到根据s1[1].age 的地址及成员名称,即可获取到改结构的首地址。即ptr = &s1[1]。



总结


  • offsetof:对于给定的一个结构的成员,获取其成员相对于首地址的偏移。


  • container_of:对于给定结构成员的地址,返回其结构体指针(所有者)首地址。


内核里面为什么要用到这两个宏呢?事实上在内核链表里面大量用到了这两个宏。


struct list_head {
 struct list_head *next, *prev;
};


linux 内核链表结构信息非常简单,只包含list_head信息,我们正式通过内核链表中的list_head 指针,获取所有者的节点信息。


list_entry(ptr,type,member)


  • list_entry 就是 container_of 宏。


  • ptr是指向该数据中list_head成员的指针,也就是存储在链表中的地址值。


  • type是数据项的类型。


  • member则是数据项类型定义中list_head成员的变量名。
相关文章
|
17天前
|
监控 Linux 应用服务中间件
探索Linux中的`ps`命令:进程监控与分析的利器
探索Linux中的`ps`命令:进程监控与分析的利器
|
18天前
|
Linux API 调度
技术笔记:Linux内核跟踪和性能分析
技术笔记:Linux内核跟踪和性能分析
|
18天前
|
算法 Linux 编译器
技术笔记:LINUX2.6.32下的进程分析
技术笔记:LINUX2.6.32下的进程分析
|
4天前
|
监控 数据挖掘 Linux
探索Linux中的`sort`命令:数据处理与分析的得力助手
`sort`命令是Linux下文本数据排序利器,用于按字典、数字顺序等对行排序。关键参数有:-n(数字排序),-r(逆序),-u(去重),-k(指定字段),-t(字段分隔符)和-o(输出到文件)。在处理大文件时注意内存使用,确保字符编码一致,灵活运用管道和重定向。通过熟练使用`sort`,能提升数据分析效率。
|
3天前
|
Linux
Linux EXPORT_SYMBOL宏详解
Linux EXPORT_SYMBOL宏详解
11 4
|
4天前
|
Linux
查看linux内核版本
在Linux中查看内核版本可使用`uname -r`、`cat /proc/version`、`lsb_release -a`、`cat /etc/*release`、`dmesg | grep Linux`、`hostnamectl`、`kernrelease`(部分系统)、`rpm -q kernel`(RPM系统)或`dpkg -l linux-image-*`(Debian系)。
8 2
|
18天前
|
运维 监控 网络协议
Linux 下的性能监控与分析技巧
在Linux环境中,命令行工具助力服务器管理和故障排查。通过示例展示如何监控网络、TCP连接、CPU及内存使用。例如,用`netstat`结合`awk`查TOP 20高频率IP访问80端口,识别DDoS迹象;`netstat -nat`统计TCP状态;`ps -aux`排序列出CPU和内存消耗大的进程;`find`加`tar`查找并压缩`.conf`文件。掌握这些命令提升运维效率。
16 1
|
21天前
|
Linux 数据处理 开发者
深入解析Linux中的paste命令:数据处理与分析的得力助手
`paste`命令在Linux中是数据处理的利器,它按列拼接多个文件内容,支持自定义分隔符和从标准输入读取。例如,合并`file1.txt`和`file2.txt`,使用`paste file1.txt file2.txt`,默认以制表符分隔;若要使用逗号分隔,可运行`paste -d &#39;,&#39; file1.txt file2.txt`。当文件行数不同时,较短文件后会填充空白行。结合管道符与其他命令使用,如`cat file1.txt | paste -s`,可按行合并内容。注意文件大小可能影响性能。
|
21天前
|
Linux 编译器 C语言
Linux 中 EXPORT_SYMBOL宏详解
Linux 中 EXPORT_SYMBOL宏详解
|
22天前
|
Linux 编译器 测试技术
探索Linux中的objcopy命令:数据处理与分析的得力助手
`objcopy`是GNU工具集中的实用程序,用于复制和转换二进制目标文件,如ELF到S-record。它支持格式转换、内容提取和修改,如移除调试信息。命令参数包括指定输入/输出格式和复制特定段。示例用途有:`objcopy -O binary input.elf output.bin`(ELF转二进制)和`objcopy -j .text input.elf output.o`(复制.text段)。使用时注意文件格式、备份原始文件并查阅文档。对于处理和分析二进制数据,`objcopy`是不可或缺的工具。