生活的天平本不平衡,只有通过努力改变其偏向。

Windows句柄表分配算法分析 zz

2009-03-31

作者:_achillis

转载请注明原作者及出处,谢谢.

前置知识:Windows句柄表的基本结构
本文以WRK1.2的代码为参考,主要分析Windows句柄表的分配算法,其实只要了解了句柄表的结构,就很容易理解在分配句柄表过程中的每一步操作是何含义,理解之后你会感觉,这个其实算不上什么算法,只能叫做一个规则吧

一、首先来看ExCreateHandleTable(),该函数创建一个HANDLE_TABLE结构;
其过程是调用ExpAllocateHandleTable()完成申请HANDLE_TABLE的工作,然后把申请到的HANDLE_TABLE放到句柄表双链中去
所有进程的HANDLE_TABLE就这样连接在一起(如果有人用过ZwQuerySystemInformation枚举系统中的所有句柄时,就是沿着 这条双向链表走的),而PspCidTable也由该函数创建,但这后又被从该双链中移除,成为一个独立的句柄表(谁让它特殊~)
//核心是下面两句
HandleTable = ExpAllocateHandleTable( Process, TRUE );//创建句柄表
InsertTailList( &HandleTableListHead, &HandleTable->HandleTableList );//放入双向链表中
=======================================================
PHANDLE_TABLE
ExpAllocateHandleTable (
IN PEPROCESS Process OPTIONAL,
IN BOOLEAN DoInit
);
过程分析:
1.申请一块PagedPool作为HANDLE_TABLE,大小为sizeof(HANDLE_TABLE)
2.为HANDLE_TABLE申请一块PagePool内存作为第一个一级表,大小为PAGE_SIZE,以后的一级表由ExpAllocateLowLevelTable来申请

  1. //设置TableCode为刚申请的一级表,这里其实隐含了句柄表为一级这个事实
  2. HandleTable->TableCode = (ULONG_PTR)HandleTableTable;
  3. //下面是对这个刚申请的一级表进行初始化
  4. HandleEntry = &HandleTableTable[0]; //第一个HANDLE_TABLE_ENTRY
  5. HandleEntry->NextFreeTableEntry = EX_ADDITIONAL_INFO_SIGNATURE;//-2,作为标志;
  6. HandleEntry->Value = 0; //对象值为0,对应于无效句柄NULL
  7. //
  8. // For duplicate calls we skip building the free list as we rebuild it manually as
  9. // we traverse the old table we are duplicating
  10. //
  11. if (DoInit) { //这个参数在普通调用时为TRUE,仅在复制句柄表时则为False,因为复制时并不需要重新分配句柄
  12. HandleEntry++; //从第二个HANDLE_TABLE_ENTRY开始
  13. //
  14. //   Now setup the free list.   We do this by chaining together the free
  15. //   entries such that each free entry give the next free index (i.e.,
  16. //   like a fat chain).   The chain is terminated with a 0.   Note that
  17. //   we’ll skip handle zero because our callers will get that value
  18. //   confused with null.
  19. //
  20. for (i = 1; i < LOWLEVEL_COUNT – 1; i += 1) {
  21. HandleEntry->Value = 0; //对象值初始化为0
  22. //FreeHandle即自由的,未被使用的句柄
  23. HandleEntry->NextFreeTableEntry = (i+1)*HANDLE_VALUE_INC; //构建FreeHandle列表,在初始化时,每一个HANDLE_TABLE_ENTRY都指向下一个句柄.这里的NextFreeTableEntry的值准确说是下一个FreeHandle,这样构成了一个单向链表一样的结构
  24. HandleEntry++;
  25. }
  26. //对最后一项作特殊处理
  27. HandleEntry->Value = 0;
  28. HandleEntry->NextFreeTableEntry = 0; //最后一项的NextFreeTableEntry为0
  29. HandleTable->FirstFree = HANDLE_VALUE_INC; //把刚初始化完的句柄表的FirstFree设为4,即第一个可用句柄
  30. }
  31. HandleTable->NextHandleNeedingPool = LOWLEVEL_COUNT * HANDLE_VALUE_INC; //一级表最大句柄
  32. //
  33. //   Setup the necessary process information
  34. //
  35. HandleTable->QuotaProcess = Process; //设置所属的Process
  36. HandleTable->UniqueProcessId = PsGetCurrentProcess()->UniqueProcessId; //调置所属Process的ProcessId
  37. HandleTable->Flags = 0;

=============================================================================================================
二、申请低级表,即最底层一级的表.每个HANDLE_TABLE的第一个一级表在创建HANDLE_TABLE时就被创建了,ExpAllocateLowLevelTable用于提供在其它时候创建一级表的支持,比如句柄表已经为二级时再申请句柄表时只需要申请创建一个一级表并加入二级表中即可.

  1. PHANDLE_TABLE_ENTRY
  2. ExpAllocateLowLevelTable (
  3. IN PHANDLE_TABLE HandleTable,
  4. IN BOOLEAN DoInit
  5. )
  6. /*++
  7. Routine Description:
  8. This worker routine allocates a new low level table
  9. Note: The caller must have already locked the handle table
  10. Arguments:
  11. HandleTable – Supplies the handle table being used
  12. DoInit – If FALSE the caller (duplicate) doesn’t need the free list maintained
  13. Return Value:
  14. Returns – a pointer to a low-level table if allocation is
  15. successful otherwise the return value is null.
  16. –*/
  17. {
  18. ULONG k;
  19. PHANDLE_TABLE_ENTRY NewLowLevel = NULL, HandleEntry;
  20. ULONG BaseHandle;
  21. //
  22. //   Allocate the pool for lower level
  23. //
  24. NewLowLevel = ExpAllocateTablePagedPoolNoZero( HandleTable->QuotaProcess,
  25. TABLE_PAGE_SIZE
  26. );//申请内存,大小为一级表的大小TABLE_PAGE_SIZE
  27. if (NewLowLevel == NULL) {
  28. return NULL;
  29. }
  30. //
  31. //   We stamp with EX_ADDITIONAL_INFO_SIGNATURE to recognize in the future this
  32. //   is a special information entry
  33. //
  34. //下面三行代码为初始化,这个同刚创建HANDLE_TABLE时创建第一个一级表时的工作基本相同,不多说
  35. HandleEntry = &NewLowLevel[0];
  36. HandleEntry->NextFreeTableEntry = EX_ADDITIONAL_INFO_SIGNATURE;
  37. HandleEntry->Value = 0;
  38. //
  39. // Initialize the free list within this page if the caller wants this
  40. //
  41. if (DoInit) {
  42. HandleEntry++;
  43. //
  44. //   Now add the new entries to the free list.   To do this we
  45. //   chain the new free entries together.   We are guaranteed to
  46. //   have at least one new buffer.   The second buffer we need
  47. //   to check for.
  48. //
  49. //   We reserve the first entry in the table to the structure with
  50. //   additional info
  51. //
  52. //
  53. //   Do the guaranteed first buffer
  54. //
  55. //这里是构建FreeHandleList,也是将每一个HANDLE_TABLE_ENTRY的NextFreeTableEntry指向下一个可用句柄.
  56. //但是由于这里不是第一个一级表,所以句柄值的计算稍有不同,需要考虑加上前面的部分
  57. BaseHandle = HandleTable->NextHandleNeedingPool + 2 * HANDLE_VALUE_INC;
  58. //BaseHandle 是当前新分配的句柄表中的最小句柄+4,即未申请本表时的最大Handle(句柄表的最大Handle即 HandleTable->NextHandleNeedingPool)再加上8,也就是说跳过了第一个用作无效标记的 HANDLE_TABLE_ENTRY(占一个句柄索引),以第二个作为新句柄表起始点的HANDLE_TABLE_ENTRY为起始点(因为第二个 HANDLE_TABLE_ENTRY才是有效的,因此从这里开始构建FreeHandleList的话,它的下一个FreeHandle应该指向第三个 HANDLE_TABLE_ENTRY,而第三个HANDLE_TABLE_ENTRY的句柄在当前句柄表内的偏移为 2*HANDLE_VALUE_INC=8)
  59. for (k = BaseHandle; k < BaseHandle + (LOWLEVEL_COUNT – 2) * HANDLE_VALUE_INC; k += HANDLE_VALUE_INC) {
  60. //k的值为BaseHandle开始,以HANDLE_VALUE_INC递增,增量为4
  61. HandleEntry->NextFreeTableEntry = k; //这里构建了FreeHandleList,可以实验观察之
  62. HandleEntry->Value = 0;
  63. HandleEntry++;
  64. }
  65. HandleEntry->NextFreeTableEntry = 0; //最后一个置0,作为结束标记
  66. HandleEntry->Value = 0;
  67. }
  68. return NewLowLevel;
  69. }

四.句柄表的扩容: 已分配的句柄表被用完时,ExpAllocateHandleTableEntrySlow被调用以分配一个新的句柄表,实现对句柄表的扩容.每次增加粒 度都是一个一级表的大小(大小为PAGE_SIZE,句柄容量为 PAGE_SIZE/sizeof(HANDLE_TABLE_ENTRY)*HANDLE_VALUE_INC=0×800),但是根据具体情况不同, 表的结构可能会发生改变,可能只是增加了一个一级表,也有可能由一级升级为二级表等等,情况比较多.搞清这个函数的调用时机对于分析该函数的流程非常重 要.

  1. BOOLEAN
  2. ExpAllocateHandleTableEntrySlow (
  3. IN PHANDLE_TABLE HandleTable,
  4. IN BOOLEAN DoInit
  5. )
  6. /*++
  7. Routine Description:
  8. This worker routine allocates a new handle table entry for the specified
  9. handle table.
  10. Note: The caller must have already locked the handle table
  11. Arguments:
  12. HandleTable – Supplies the handle table being used
  13. DoInit – If FALSE then the caller (duplicate) doesn’t need the free list built
  14. Return Value:
  15. BOOLEAN – TRUE, Retry the fast allocation path, FALSE, We failed to allocate memory
  16. –*/
  17. {
  18. ULONG i,j;
  19. PHANDLE_TABLE_ENTRY NewLowLevel;
  20. PHANDLE_TABLE_ENTRY *NewMidLevel;
  21. PHANDLE_TABLE_ENTRY **NewHighLevel;
  22. ULONG NewFree, OldFree;
  23. ULONG OldIndex;
  24. PVOID OldValue;
  25. ULONG_PTR CapturedTable = HandleTable->TableCode;
  26. ULONG TableLevel = (ULONG)(CapturedTable & LEVEL_CODE_MASK); //当前句柄表的级数
  27. PAGED_CODE();
  28. //
  29. // Initializing NewLowLevel is not needed for
  30. // correctness but without it the compiler cannot compile this code
  31. // W4 to check for use of uninitialized variables.
  32. //
  33. NewLowLevel = NULL;
  34. CapturedTable = CapturedTable & ~LEVEL_CODE_MASK; //当前句柄表的基址
  35. if ( TableLevel == 0 ) {//当前是一级表,这时再增加容量就需要升级为二级表了
  36. //
  37. //   We have a single level. We need to ad a mid-layer
  38. //   to the process handle table
  39. //
  40. //分配一个二级表,ExpAllocateMidLevelTable的流程前面已经分析过了,它同时还分配了一个新的一级表,放在NewMidLevel[0]中
  41. NewMidLevel = ExpAllocateMidLevelTable( HandleTable, DoInit, &NewLowLevel );
  42. if (NewMidLevel == NULL) {
  43. return FALSE;
  44. }
  45. //
  46. //   Since ExpAllocateMidLevelTable initialize the
  47. //   first position with a new table, we need to move it in
  48. //   the second position, and store in the first position the current one
  49. //
  50. NewMidLevel[1] = NewMidLevel[0]; //把刚申请到的一级表放入第二个位置
  51. NewMidLevel[0] = (PHANDLE_TABLE_ENTRY)CapturedTable; //第一个位置存放CapturedTable,即最初的一级表
  52. //之所以按这个顺序放置,是为了保证位置靠前的句柄表确实已经满载~
  53. //
  54. //   Encode the current level and set it to the handle table process
  55. //
  56. CapturedTable = ((ULONG_PTR)NewMidLevel) | 1; //当前新的TableCode值,最低位置1,这是二级表的标志
  57. OldValue = InterlockedExchangePointer( (PVOID *)&HandleTable->TableCode, (PVOID)CapturedTable );//设置新的TableCode值
  58. } else if (TableLevel == 1) {//已经是二级表,则需要看具体情况是再分配一个一级表就可以了,还是可能升级为三级表
  59. //
  60. //   We have a 2 levels handle table
  61. //
  62. PHANDLE_TABLE_ENTRY *TableLevel2 = (PHANDLE_TABLE_ENTRY *)CapturedTable;
  63. //
  64. //   Test whether the index we need to create is still in the
  65. //   range for a 2 layers table
  66. //
  67. i = HandleTable->NextHandleNeedingPool / (LOWLEVEL_COUNT * HANDLE_VALUE_INC); //i是当前一级表的个数
  68. if (i < MIDLEVEL_COUNT) { //若比二级表的最大容量小,则只需要再分配一个一级表(LowLevelTable)就可以了
  69. //
  70. //   We just need to allocate a new low-level
  71. //   table
  72. //
  73. NewLowLevel = ExpAllocateLowLevelTable( HandleTable, DoInit ); //再申请一个一级表
  74. if (NewLowLevel == NULL) {
  75. return FALSE;
  76. }
  77. //
  78. //   Set the new one to the table, at appropriate position
  79. //
  80. OldValue = InterlockedExchangePointer( (PVOID *) (&TableLevel2[i]), NewLowLevel ); //放入二级表中
  81. EXASSERT (OldValue == NULL);
  82. } else {//已达到二级表最大数目,需要升级至三级表
  83. //
  84. //   We exhausted the 2 level domain. We need to insert a new one
  85. //
  86. NewHighLevel = ExpAllocateTablePagedPool( HandleTable->QuotaProcess,
  87. HIGHLEVEL_SIZE
  88. );//申请一个表作为三级表
  89. if (NewHighLevel == NULL) {
  90. return FALSE;
  91. }
  92. NewMidLevel = ExpAllocateMidLevelTable( HandleTable, DoInit, &NewLowLevel );//给这个三级表申请一个二级表,至于为什么,原因前面分析ExpAllocateMidLevelTable时就分析过了,只不那是给二级表申请了一个一级表,道理是一样的~~
  93. if (NewMidLevel == NULL) {
  94. ExpFreeTablePagedPool( HandleTable->QuotaProcess,
  95. NewHighLevel,
  96. HIGHLEVEL_SIZE
  97. );
  98. return FALSE;
  99. }
  100. //
  101. //   Initialize the first index with the previous mid-level layer
  102. //
  103. NewHighLevel[0] = (PHANDLE_TABLE_ENTRY*)CapturedTable;//把原来的二级表地址放入三级表的第一个位置
  104. NewHighLevel[1] = NewMidLevel; //刚申请的二级表放在第二个位置
  105. //
  106. //   Encode the level into the table pointer
  107. //
  108. CapturedTable = ((ULONG_PTR)NewHighLevel) | 2; //设置TableCode低两位为2,即三级表的标志
  109. //
  110. //   Change the handle table pointer with this one
  111. //
  112. OldValue = InterlockedExchangePointer( (PVOID *)&HandleTable->TableCode, (PVOID)CapturedTable );//设置新的TableCode
  113. }
  114. } else if (TableLevel == 2) {//当前已经是三级表了,情况分为三种:表全满,二级表满,一级表满
  115. //
  116. //   we have already a table with 3 levels
  117. //
  118. ULONG RemainingIndex;
  119. PHANDLE_TABLE_ENTRY **TableLevel3 = (PHANDLE_TABLE_ENTRY **)CapturedTable;
  120. i = HandleTable->NextHandleNeedingPool / (MIDLEVEL_THRESHOLD * HANDLE_VALUE_INC); //三级表中二级表的个数
  121. //
  122. //   Check whether we exhausted all possible indexes.
  123. //
  124. if (i >= HIGHLEVEL_COUNT) { //二级表个数超出三级表的容易则失败!(实际上达不到这个数)
  125. return FALSE;
  126. }
  127. if (TableLevel3[i] == NULL) { //确定这个位置可用,还没有放置二级表指针, 这也表明需要申请一个新的二级表了
  128. //
  129. //   The new available handle points to a free mid-level entry
  130. //   We need then to allocate a new one and save it in that position
  131. //
  132. NewMidLevel = ExpAllocateMidLevelTable( HandleTable, DoInit, &NewLowLevel );//申请一个二级表
  133. if (NewMidLevel == NULL) {
  134. return FALSE;
  135. }
  136. OldValue = InterlockedExchangePointer( (PVOID *) &(TableLevel3[i]), NewMidLevel );//放入刚才的位置
  137. EXASSERT (OldValue == NULL);
  138. } else { //若TableLevel3[i]不为NULL,则表明TableLevel3[i]这个二级表已存在,但还没有放满,只需要给这个二级表再申请一个一级表就可以了
  139. //
  140. //   We have already a mid-level table. We just need to add a new low-level one
  141. //   at the end
  142. //
  143. RemainingIndex = (HandleTable->NextHandleNeedingPool / HANDLE_VALUE_INC) -
  144. i * MIDLEVEL_THRESHOLD;
  145. j = RemainingIndex / LOWLEVEL_COUNT;//计算出新的一级表在TableLevel3[i]这个二级表中的偏移
  146. NewLowLevel = ExpAllocateLowLevelTable( HandleTable, DoInit ); //只需要申请一个一级表
  147. if (NewLowLevel == NULL) {
  148. return FALSE;
  149. }
  150. OldValue = InterlockedExchangePointer( (PVOID *)(&TableLevel3[i][j]) , NewLowLevel );//把刚申请的一级表放入TableLevel3[i]这个二级表中
  151. EXASSERT (OldValue == NULL);
  152. }
  153. }
  154. //
  155. // This must be done after the table pointers so that new created handles
  156. // are valid before being freed.
  157. //
  158. OldIndex = InterlockedExchangeAdd ((PLONG) &HandleTable->NextHandleNeedingPool,
  159. LOWLEVEL_COUNT * HANDLE_VALUE_INC);// 设置新的NextHandleNeedingPool,增量为一个一级句柄表的句柄容量(即一级表中HANDLE_TABEL_ENTRY的个数再乘 4),并把原来的NextHandleNeedingPool值放入OldIndex,也就是说,OldIndex是曾经的句柄值上限
  160. if (DoInit) {//这里对刚申请的一级表进行一些初始化工作
  161. //
  162. // Generate a new sequence number since this is a push
  163. //
  164. OldIndex += HANDLE_VALUE_INC + GetNextSeq();//GetNextSeq()的结果为0,所以相当于只加了一个HANDLE_VALUE_INC,即4,此时的OldIndex是新分配的句柄表中的最小句柄
  165. //
  166. // Now free the handles. These are all ready to be accepted by the lookup logic now.
  167. //
  168. while (1) {
  169. OldFree = ReadForWriteAccess (&HandleTable->FirstFree); //OldFree是原来的FirstFree的值
  170. NewLowLevel[LOWLEVEL_COUNT - 1].NextFreeTableEntry = OldFree; // 把一级表的最后一项的NextFreeHandle指向以前的HandleTable->FirstFree, 这就相当于把原来的FreeHandleList连在了新申请的句柄表的FreeHandleList链后面,成为一条新的FreeHandleList
  171. //
  172. // These are new entries that have never existed before. We can’t have an A-B-A problem
  173. // with these so we don’t need to take any locks
  174. //
  175. NewFree = InterlockedCompareExchange ((PLONG)&HandleTable->FirstFree,
  176. OldIndex,//用为新的FirstFree的值放入,新申请的句柄将从这个值开始
  177. OldFree);
  178. if (NewFree == OldFree) {//成功,就跳出这个循环了
  179. break;
  180. }
  181. }
  182. }
  183. return TRUE;
  184. }

三、当需要申请一个新的二级表(MidLevelTable)时,调用ExpAllocateMidLevelTable函数

  1. PHANDLE_TABLE_ENTRY *
  2. ExpAllocateMidLevelTable (
  3. IN PHANDLE_TABLE HandleTable,
  4. IN BOOLEAN DoInit,
  5. OUT PHANDLE_TABLE_ENTRY *pNewLowLevel
  6. )
  7. /*++
  8. Routine Description:
  9. This worker routine allocates a mid-level table. This is an array with
  10. pointers to low-level tables.
  11. It will allocate also a low-level table and will save it in the first index
  12. Note: The caller must have already locked the handle table
  13. Arguments:
  14. HandleTable – Supplies the handle table being used
  15. DoInit – If FALSE the caller (duplicate) does not want the free list build
  16. pNewLowLevel – Returns the new low level table for later free list chaining
  17. Return Value:
  18. Returns a pointer to the new mid-level table allocated
  19. –*/
  20. {
  21. PHANDLE_TABLE_ENTRY *NewMidLevel;
  22. PHANDLE_TABLE_ENTRY NewLowLevel;
  23. NewMidLevel = ExpAllocateTablePagedPool( HandleTable->QuotaProcess,
  24. PAGE_SIZE
  25. ); //申请一块内存作为MidLevel,即二级表,大小为PAGE_SIZE,用以存放一级表的指针
  26. if (NewMidLevel == NULL) {
  27. return NULL;
  28. }
  29. //
  30. //   If we need a new mid-level, we’ll need a low-level too.
  31. //   We’ll create one and if success we’ll save it at the first position
  32. //
  33. NewLowLevel = ExpAllocateLowLevelTable( HandleTable, DoInit ); //申请一个一级表.
  34. //有人问过为什么这个函数在申请二级表时同时还会申请一个一级表,看这个函数的调用时机就知道了.
  35. //调用过程ExCreateHandle->ExpAllocateHandleTableEntry->ExpAllocateHandleTableEntrySlow->ExpAllocateMidLevelTable
  36. //对ExCreateHandle更具体的分析,那是句柄分配的知识,稍后再说,以免偏题,现在只须知道调用ExpAllocateHandleTableEntrySlow时则表明句柄已达上限,需要再申请新的句柄表就行了
  37. //而ExpAllocateHandleTableEntrySlow调用ExpAllocateMidLevelTable的第一个时机是TableLevel=0且句柄已达上限的时候,
  38. // 这时候需要申请这个二级表,那就说明一级表不够用了(三级表和二级表都只放指针,一级表中才是真正放内容的),需要再申请一个一级表,而两个一级表就使得 句柄表的级数跃升为两级(MidLevel).所以,申请MidLevel的Table时其实就是稍带着把再申请一个一级表的工作也做好了(同样的,前面 已经看到,申请HANDLE_TABLE时也是同时申请好了第一个一级表),这只是一级表跃升为二级表时的一个必做工作,仅此而已.总的说,二级表也只是 框架,它有了内容(一级表)才能真正去放东西
  39. //调用ExpAllocateMidLevelTable的另一种情况是此时TableLevel=2,但最后一个二级表已放满了.此时要申请一个一级表就需要先申请一个新的二级表,情况和前面类似了
  40. if (NewLowLevel == NULL) {
  41. ExpFreeTablePagedPool( HandleTable->QuotaProcess,
  42. NewMidLevel,
  43. PAGE_SIZE
  44. );
  45. return NULL;
  46. }
  47. //
  48. //   Set the low-level table at the first index
  49. //
  50. NewMidLevel[0] = NewLowLevel;// 把这个新的一级表放入NewMidLevel[0],这个值后来则被放入了NewMidLevel[1],后面会分析到.而NewMidLevel[0] 则存放最初的一级表(即升级为二级表之前的那个一级表),详细代码见ExpAllocateHandleTableEntrySlow()
  51. *pNewLowLevel = NewLowLevel;
  52. return NewMidLevel; //新的二级表地址作为返回值
  53. }
作者:lonkil | 分类目录:编程开发 | 标签:

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>