【学习札记NO.00003】基于libc

编程入门 行业动态 更新时间:2024-10-18 18:26:08

【学习<a href=https://www.elefans.com/category/jswz/34/1753535.html style=札记NO.00003】基于libc"/>

【学习札记NO.00003】基于libc

GITHUB PAGES ADDRESS

【学习札记NO.00003】基于libc-2.23版本的malloc源码简易分析 - Part-I - 堆内存的基本组织形式 by arttnba3

  • [GITHUB PAGES ADDRESS](.23-PART-I/)
  • 0x00.堆内存的组织形式
    • 一、malloc_chunk
      • [The \_\_alignof\_\_ operator](.htm?view=kc#ToC_180)
    • 二、chunk相关宏
      • 1.chunk size相关宏
        • 宏:offsetof
      • 2.memory request相关宏
        • 关于chunk间的内存复用及request2size计算相关事项
      • 3.chunk标志位相关宏
        • ①标志位定义及相关宏
        • ②标志位操作相关宏及其他宏
    • 三、Bins:存放闲置chunk的数组
      • 1.bins通用宏
      • 2.bins相关定义宏
        • ①unsorted bin相关宏
        • ②small bins相关宏
        • ③large bins相关宏
      • 3.unlink:从bins中取出chunk
          • \_\_builtin\_expect(expr, var):分支预测优化
          • malloc\_printerr()
      • 4.binmap:用来标识bin状态(是否为空)的数组
    • 四、Fastbins:快速存取chunk的数组
      • fastbin相关宏
      • fastbin size详解
    • 五、malloc\_par:堆管理器参数
      • mp\_:记录ptmalloc相关参数的malloc\_par结构体
    • 六、heap\_info:Heap Header(for heap allocated by mmap)
      • heap\_info相关宏
    • 七、arena:线程内存池
      • 1.malloc_state结构体
        • ①mutex:互斥锁
        • ②flags:标志位
          • flags标志位相关
        • ③fastbinY:存放fastbin chunk的数组
        • ④top:指向Top Chunk的指针
        • ⑤last\_remainder:chunk切割中的剩余部分
        • ⑥bins:存放闲置chunk的数组
        • ⑦binmap:用以表示binmap的数组
        • ⑧next:指向下一个arena的指针
        • ⑨next\_free:指向下一个空闲的arena的指针
        • ⑩attached\_threads:与该arena相关联的线程数
        • ⑪system\_mem:记录当前arena在堆区中所分配到的内存的总大小
        • ⑫ max\_system\_mem:记录当前arena在堆区中所分配到的内存的总大小的最大值
      • 2.arena相关变量
        • ①thread\_arena:每个线程所对应的arena
        • \_\_thread:线程变量
        • attribute_tls_model_ie
          • Thread-Local Storage:线程本地存储(TLS)
        • \_\_attribute\_\_
        • ②narenas:arena数量
        • ③main\_arena:初始主线程arena
        • ④free\_list:空闲arena链表(头结点)
        • ⑤ arena\_mem:非主线程的arena所占用的内存空间总大小
      • 3.arena相关函数与宏
        • ①malloc\_init\_state():初始化arena内成员
        • ②\_int\_new\_arena():创建一个新的arena
          • LIBC\_PROBE:「LIBC探针」
          • System Tap:「内核探测工具」
        • ③get\_free\_list():尝试从free\_list中获取一个空闲arena
        • ④arena\_get():获得一个arena
          • do{...}while(0):约定俗成书写形式
        • ⑤arena\_lock():将arena上锁
        • ⑥arena\_get2():遍历free\_list,若无合适则尝试获取一个新的arena或使用已有arena
          • \_\_glibc\_likely(expr) && \_\_glibc\_unlikely(expr):分支预测优化(封装宏)
          • internal\_function
          • catomic_compare_and_exchange_bool_acq
          • catomic_decrement
        • ⑦reused\_arena():寻找可用arena上锁后返回
        • ⑧detach\_arena():将arena关联线程数减一
        • ⑨arena\_for\_chunk():获取一个堆块对应的arena

让我们先从chunk讲起…

推荐到我的博客去阅读这篇文章,csdn有的地方的markdown解析实在稀烂…

0x00.堆内存的组织形式

一、malloc_chunk

思来想去还是先从最简单的堆块的基本组织形式——malloc_chunk结构体开始讲起,同时也事先讲完一些通用宏定义,省得后面再不断的递归套娃回来看chunk相关的各种定义←因为这个人真的遇到了这样的情况

通常情况下,我们将向系统所申请得到的内存块称之为chunk,在ptmalloc的内部使用malloc_chunk结构体来表示,代码如下:

struct malloc_chunk {INTERNAL_SIZE_T      prev_size;  /* Size of previous chunk (if free).  */INTERNAL_SIZE_T      size;       /* Size in bytes, including overhead. */struct malloc_chunk* fd;         /* double links -- used only if free. */struct malloc_chunk* bk;/* Only used for large blocks: pointer to next larger size.  */struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */struct malloc_chunk* bk_nextsize;
};

首先我们先看一些相关的宏定义:

#ifndef INTERNAL_SIZE_T
#define INTERNAL_SIZE_T size_t
#endif/* The corresponding word size */
#define SIZE_SZ                (sizeof(INTERNAL_SIZE_T))/*MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks.It must be a power of two at least 2 * SIZE_SZ, even on machinesfor which smaller alignments would suffice. It may be defined aslarger than this though. Note however that code and data structuresare optimized for the case of 8-byte alignment.
*/#ifndef MALLOC_ALIGNMENT
# if !SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_16)
/* This is the correct definition when there is no past ABI to constrain it.Among configurations with a past ABI constraint, it differs from2*SIZE_SZ only on powerpc32.  For the time being, changing this iscausing more compatibility problems due to malloc_get_state andmalloc_set_state than will returning blocks not adequately aligned forlong double objects under -mlong-double-128.  */#  define MALLOC_ALIGNMENT       (2 *SIZE_SZ < __alignof__ (long double)      \? __alignof__ (long double) : 2 *SIZE_SZ)
# else
#  define MALLOC_ALIGNMENT       (2 *SIZE_SZ)
# endif
#endif/* The corresponding bit mask value */
#define MALLOC_ALIGN_MASK      (MALLOC_ALIGNMENT - 1)

大致如下:

  • INTERNAL_SIZE_T宏展开后其实就是size_t,32位下为4字节,64位下为8字节SIZE_SZ为其别名
  • MALLOC_ALIGNMENT则定义了chunk在内存中对齐的字节数,一般来说算出来都是对2*SIZE_SZ对齐,即32位下8字节对齐,64位下16字节对齐
  • MALLOC_ALIGEN_MASK的值则是MALLOC_ALIGENMENT - 1,笔者猜测其表示的是标志位全满的标志位值掩码,用以进行后续的标志位清除运算等操作

The __alignof__ operator

The __alignof__ operator is a language extension to C99 and Standard C++ that returns the number of bytes used in the alignment of its operand. The operand can be an expression or a parenthesized type identifier. If the operand is an expression representing an lvalue, the number returned by alignof represents the alignment that the lvalue is known to have. The type of the expression is determined at compile time, but the expression itself is not evaluated. If the operand is a type, the number represents the alignment usually required for the type on the target platform.

(from IBM Knowledge Center)

大意是说__alignof__运算符是对C99及标准C++的拓展,用以返回运算对象所占用空间的字节数

结构体中一共有六个变量,大致如下:

  • prev_size:用以保存前一个内存物理地址相邻的chunk的size,仅在该chunk为free状态时会被使用到
  • size:顾名思义,用以保存这个chunk的总的大小,即同时包含chunk头prev_size + size和chunk剩余部分的大小
  • fd&&bk仅在在chunk被free后使用,用以连接其他的chunk,也就是说当chunk处于被使用的状态时该字段无效,被用以存储用户的数据
  • fd_nextsize&&bk_nextsize:仅在在chunk被free后使用,用以连接其他的chunk

后面我们还会再详细讲解这几个变量的相关内容,这里仅作一简览

由于最后的两个变量仅用于较大的free的chunk,故我们先暂且忽略

那么我们便可以知道:一个chunk在内存中大概是长这个样子的

当然,我个人更喜欢用如下的结构来表示,问就是

更多推荐

【学习札记NO.00003】基于libc

本文发布于:2024-03-12 11:46:26,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:札记   libc

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!