我无法从概念上理解在系统调用结束时发生了什么,以及为什么。我理解getstk.c方法返回可用空间的最高内存地址,但不了解某些代码正在做什么。对此的一些澄清将是伟大的。在星号中强调了我不完全理解的代码区域。
/* getstk.c - getstk */
#include <xinu.h>
/*------------------------------------------------------------------------
* getstk - Allocate stack memory, returning highest word address
*------------------------------------------------------------------------
*/
char *getstk(
uint32 nbytes /* size of memory requested */
)
{
intmask mask; /* saved interrupt mask */
struct memblk *prev, *curr; /* walk through memory list */
struct memblk *fits, *fitsprev; /* record block that fits */
mask = disable();
if (nbytes == 0) {
restore(mask);
return (char *)SYSERR;
}
nbytes = (uint32) roundmb(nbytes); /* use mblock multiples */
prev = &memlist;
curr = memlist.mnext;
fits = NULL;
fitsprev = NULL; /* to avoid a compiler warning */
while (curr != NULL) { /* scan entire list */
if (curr->mlength >= nbytes) { /* record block address */
fits = curr; /* when request fits */
fitsprev = prev;
}
prev = curr;
curr = curr->mnext;
}
if (fits == NULL) { /* no block was found */
restore(mask);
return (char *)SYSERR;
}
if (nbytes == fits->mlength) { /* block is exact match */
fitsprev->mnext = fits->mnext;
**} else { /* remove top section */
fits->mlength -= nbytes;
fits = (struct memblk *)((uint32)fits + fits->mlength);
}**
memlist.mlength -= nbytes;
restore(mask);
**return (char *)((uint32) fits + nbytes - sizeof(uint32));**
}
struct memblk可以在这里找到:
struct memblk { /* see roundmb & truncmb */
struct memblk *mnext; /* ptr to next free memory blk */
uint32 mlength; /* size of blk (includes memblk)*/
};
extern struct memblk memlist; /* head of free memory list */
为什么他们返回fit + nbytes-sizeof(uint32)?他们为什么要输入(一个结构)来输入uint32?
答案 0 :(得分:1)
if (nbytes == fits->mlength) { /* block is exact match */
fitsprev->mnext = fits->mnext;
**} else { /* remove top section */
fits->mlength -= nbytes;
fits = (struct memblk *)((uint32)fits + fits->mlength);
}**
memlist.mlength -= nbytes;
restore(mask);
**return (char *)((uint32) fits + nbytes - sizeof(uint32));**
如果找到完美匹配,则只会从空闲列表中删除该块。如果找到更大的块,则块被分成两个块:比原始块(nbytes
)小的空闲块fits->mlength -= nbytes
;以及在新的空闲块(nbytes
)之后开始的已分配的fits = (struct memblk *)((uint32)fits + fits->mlength)
块,由函数返回。
为什么他们返回fit + nbytes-sizeof(uint32)?他们为什么要输入(一个结构)来输入uint32?
由于在这种情况下堆栈增长,函数返回一个指向堆栈顶部的指针,即指定块的末尾的单词,即:
(uint32)fits /* start of allocated block */ + nbytes /* size of allocated block */ - sizeof(uint32) /* size of a word */
对(uint32)
的强制转换是使用整数算术而不是指针算术,否则fits+1
将产生一个指向sizeof(struct memblk)
超过fits
的指针。转换为(char *)
可能更具惯用性。