汇编中的控制结构:循环

风行水上 @ 2013-12-26 11:31:44
标签:

    循环

    循环基本上是通过至少两个跳转命令来实现的:

    • 一个程序段尾部的jmp跳回到程序段的开始,从而实现循环。
    • 一个程序段中间的跳转跳出到程序段结束后的下一条指令,从而实现循环的结束
    • continue语句就相当于上面第一种情况的跳转
    • break语句就相当于上面第二种情况的跳转

    下面这个循环的例子,来自 一个MBR Record的反汇编

     0743:	8b f0         mov    si,ax                 # char *buf = 0x0700 + AL;
                                                       # do{
     0745:	ac            lods   al,BYTE PTR ds:[si]   #   char c = *buf; buf++;
     0746:	3c 00         cmp    al,0x0                #   if(c == '\0') break; 
     0748:	74 09         je     0x753                 #
     074a:	bb 07 00      mov    bx,0x7                #
     074d:	b4 0e         mov    ah,0xe                #
     074f:	cd 10         int    0x10                  #   putc(c);
     0751:	eb f2         jmp    0x745                 # }while(1);
    
     0753:	f4            hlt                          # halt
    

    所有的循环语句,不管是for还是while,或者do..while,都可以整理为下面的基本形式:

    statements_outside;
    while(1) { 
      statements_inside;
      if(expr2) break;
      if(expr1) continue;
      statements_inside;
    }
    statements_outside;
    

    转换成汇编就是

    ......   :   statements_outside    # outside the loop
    offset-0 :   statements_inside     # start the loop
    ......   :   expr2
    ......   :   je offset-P           # break: 2nd type jump, break the loop
    ......   :   expr1
    ......   :   je offset-0           # continue: 1st type jump, continue the loop
    ......   :   statements_inside
    offset-N :   jmp offset-0          # 1st type jump, continue the loop
    offset-P :   statements_outside    # outside the loop      
    
    标签:

      分享到:
      comments powered by Disqus

      24/26ms