Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding the container_of Macro in Linux Kernel Development

Tech 1

The container_of macro, defined in kernel.h, serves a crucial role in Linux kernel programming by enabling retrieval of a structure's address from its member's address:

/**
 * container_of - Get the container structure from a member pointer
 * @ptr: Pointer to the structure member
 * @type: Type of the containing structure
 * @member: Name of the member within the structure
 */
#define container_of(ptr, type, member) ({             \
         const typeof( ((type *)0)->member ) *__mptr = (ptr);     \
         (type *)( (char *)__mptr - offsetof(type,member) );})

Key components in this implementation:

  1. typeof: A GCC extension that determines a variable's type at compile time
  2. offsetof: Defined in stddef.h, calculates the byte offset of a member within its sturcture
#define offsetof(STRUCT_TYPE, MEMBER) ((size_t) &((STRUCT_TYPE *)0)->MEMBER)

The offsetof macro works by treating address 0 as the base of the structure, then taking the address of the specified member. This yields the member's byte offset from the structure's start.

Breaking down container_of:

  1. The first line creates a type-safe pointer to the member:

    const typeof( ((type *)0)->member ) *__mptr = (ptr);
    

    This ensures type safety by deriving the member's type through:

    • Casting 0 to a pointer of the container type
    • Accessing the member
    • Using typeof to get the member's type
  2. The second line calculates the container's address:

    (type *)( (char *)__mptr - offsetof(type,member) );
    

    This converts the member pointer to a byte pointer, subtracts the member's offset, and casts the result back to the container type.

Tags: Linuxkernelc

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.