CS: APP chapter 3 notes: (variable) stack frame

Mirror from my personal blog

Introduction

Chapter III of CS: APP mainly describes x86_64 assembly in details, which gives a dictionary-like introduction. Nevertheless, the reason why performing this chapter is to give a vivid adhere of chapter V. In this post, I just elaborate a small part introduced by a few of section, that is the runtime stack.Refers to section 3.7~3.10, Stack frame is a major part in procedure calling and manipulation. It stores variables, procedure return address, and any thing may be pushed in according to complier’s flavor.

Big picture

csapp_big.jpg

Stack frame is a memory structure holds procedure. The main function of it is similar to the figure delivered above:

  • control transfer,
  • data transfer,
  • local variables storage.

Notes: Regarding the array and struct or union, however, they are just stored in memory, without being specified whether should be stored in stack or heap file.

Every function refers to a particular interval of stack. As figured in the picture above, stack stores arguments for the calling of next procedure, caller preserve variable in register and memory and return address of the caller, which note as the PC back point.

When we combine control and data together, it will be more complex than before. That is what we refer as variable stack frame, and another miscellaneous.

Control transfer

Control transfer of procedure refers to the function calling. Suppose that function P() wonna call function Q(), once you embody this process, the program should pass some arguments, transfer the PC of %rip to the function Q(), then it go through the instructions in Q(), at last go back to the origin address of %rip when meet ret, which means that return the funtion P().

In x86_64 instruction set, there are three control instructions:

Instruction Description
call Label Procedure call
call *Operand ;;
ret Return from call

The call instruction has a target indicating the address of the instruction where the called procedure starts. Its operand, which is the address, could be direct or indirect. Go back to figure 3.3 could get more details.

Suppose we have details of function below:

Q:
    0x400540    addq %rdi, %rdi
    0x400543    movq %rdi, %rax
    0x400546    ret
    
P:
    0x400560    movq $-1, %rdi
    0x400563    call Q
    0x400568    ret
-------Origin status before call-------
%rsp: 0x7fffffffe888 --> 0x0
%rip: 0x400560
---------------------------------------

-------After execute call--------------
%rsp: 0x7fffffffe880 --> 0x400568(The address of the next ins of call)
%rip: 0x400540 (The atart of Q)
---------------------------------------

------------After ret------------------
%rsp: 0x7fffffffe888 --> 0x0
%rip: 0x400568 (last ins of P)
---------------------------------------

In this simple case, once P call Q, P push its next instruction address as its return address to the stack, then %rip gets start address of Q. When meeting ret, %rip get that address from stack then add address of %rsp according to the size of the cell. It is easy, right?

Data transfer

When passing control to another procedure, we usually pass arguments to the callee one, so as to evaluate the data then get target result. As is mentioned before, we refer %rdi as the 1st argument, %rsi the second, and so on. It is a convention of how x86-64 pass arguments. Marked in details, as below:

Argument sequence Registers notes
1st %rdi few bits portable
2nd %rsi could be accept
3rd %rdx
4th %rcx
5th %r8
6th %r9
more than 6 STORE IN STACK

The point here is, also combine the control transmission, the caller should push it’s variable stored in callee saved registers, set the argument registers into target arguments, after preparing for the function call, the PC go to the target procedure.

As an example:

proc:
    pushq %rbp
    movq %rsp, %rbp  # %rbp is a caller saved register
    add  %edi, %esi  # add %rdi to %rsi
    add  %rsi, %rdx  # ---
    add  %rdx, %rcx  # ---
    sub  %rcx, %r8   # ---
    movq %r8, %rax   # ---
    popq %rbp
    ret              # return
    
call_proc:
    sub   $16, %rsp
    movq  %edi,  8(%rsp)
    xorq  %edi,  %edi
    add   $0x8,  %edi
    movq  $0x10, %esi
    movq  %0x43(%rsp),   %rdx
    movq  $0x125 %rcx
    call proc
    movq  (%rsp), %edi
    addq  %edi,  %rax
    ret
    
# -------- stack result ---------
# |             |   orig %edi   | 8
# |          (unused)           | 0
# |        return address       | -
# |    orig rbp:     0x0        | callee - 8
# -------------------------------

Notes: the unused space is prepare for SIMD usage. On this stage, we can ignore it.

The caller saved register %rbp is pushed and set it as origin stack start position.

Local variable storage

There many example that variable are stored in registers, but at times that local variable should be load in memory. The common cases is:

  • There are not enough registers to hold all of the local data
  • The address operator ‘&’ is applied to local variable, and hense we must be able to generate an address for it
  • Some of the local variables are arrays or structures so that it should be accessed as array or structure references.

As for example code, please refer Figure 3.32

In convention, the former variable should be pushed in the higher address of stack and the later ones could be set in the lower ones. Such as:

|_____________________|
|___x2____|____x1_____| 16
|_________x3__________| 8
|_______________|__x4_| 0

Alignment

Many computer systems place restrictions on the allowable addresses for primitive data types, requiring that the address for some objects must be a multiple of some value K. Such restrictions simplify the design of hardware forming the interface between the processor and the memory system. Also, address of stack frame do the same thing, so as to be refered in a correct way. As an example of Practice Problem 3.49,

+------------------------+
+    return address      +  8
+------------------------+
+    saved %rbp          +  0
+------------------------+
+       (Unused)         + -8
+------------------------+
+                        + e1
+------------------------+
+                        +
+            P           + 8n bytes
+                        +
+------------------------+
+                        + e2
+------------------------+

Every part of the stack frame should be a multiple of 8, so that e1+P+e2 should be a multiple of 16, hense we could embed a slot of memory which address is a multiple of 8.

Variable-Size Stack Frames

The variable-size stack frames means that the size of stack frame could not be determined at compile time. Further more, the variable, maybe array of struct, should be referenced by its address. Therefore, we should use a technique of managing such condition.

As Figure 3.43 :

long vframe(long n, long idx, long *q) {
    long i;
    long *p[n];
      p[0] = &i;
      for (i = 1; i < n; i++)
      p[i] = q;
      return *p[idx];
}

Portions of generated assembly code:

vframe:
    pushq    %rbp        # Set old %rbp
    movq    %rsp, %rbp    # Set frame pointer
    subq    $16, %rsp    # Allocate space for array p
    leaq    22(, %rdi, 8), %rax    # Make it to be a multiple of 16
    andq    $-16, %rax
    subq    %rax, %rsp    # Allocate space for array p
    leaq    7(%rsp), %rax
    shrq    $3, %rax
    leaq    0(, %rax, 8), %r8
    movq    %r8, %rcx
    
    # .....
    
.L3:
    movq    %rdx, (%rcx, %rax, 8)    # Set p[i] to q
    addq    $1, %rax                 # Increment i
    movq    %rax, -8(%rbp)            # Store on the stack
.L2:
    movq    -8(%rbp), %rax            # Retrieve i
    cmpq    %rdi, %rax
    jl        .L3
    
#    .....
    leave
    ret
Note the way to refer the array is that, it refer it by pointer register %rbp

At last of the program, it restore the original pointer to the %rsp, then pop %rbp to restore the caller’s frame.

movq  %rbp, %rsp    # Set stack pointer to beginning of frame
popq  %rbp          # Restore

This instruction combination has the effect of deallocating the entire stack frame.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容