免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 25655 | 回复: 66
打印 上一主题 下一主题

虚拟机源码分析 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-01-16 11:59 |只看该作者 |倒序浏览
1)虚拟机是什么?“虚拟机”的概念其实很广,最常见的有以下两种虚拟机,第一种是模拟“裸机”运行的虚拟机,这样的虚拟机有VMWAREVirturePC,Bochs等,另一种是模拟操作系统运行情况的虚拟机,这样的虚拟机有Wine,JVM(java虚拟机)。其实,虚拟机就是一个中间层,可以理解为是两种环境的桥梁,如果把虚拟机的概念抽象一点描述,可以认为虚拟机是在某一个环境上模拟另一种环境运行情况的软件,这样的环境可以是不同的cpu,不同的os....等等。
    这里选择的是两个非常简单的虚拟机,一个是<<编译原理与实践>;>;一书中自带的TM虚拟机,另一个是<<程序员>;>;杂志2003年第六期里的一篇文章<<一个小型虚拟机的实现>;>;中实现的虚拟机,两者都有一个共同点,就是两者都是在汇编语言级别虚拟cpu运行情况的虚拟机,正因为这两个虚拟机的如此定位,所以在实现或者阅读这两个虚拟机的时候,你不得不从cpu的角度去思考问题,你必须对cpu的运行情况有了解,反过来说,阅读这两个虚拟机的源码也可以加深对cpu工作原理以及汇编语言的理解。这两个虚拟机的源码都可以在网上找到,前者在http://www.mathcs.sjsu.edu/faculty/louden/cmptext/,而后者可以在CSDN的网站上查找2003年第六期的源码。值得一提的是,CS:APP(<<深入理解计算机系统>;>;)一书中也有一章专门讲述CPU的运行原理,而且作者也自己实现了一个CPU,而且还是流水线型,所以这个虚拟机功能更酷也更加强大,因为作者自己定义了一种硬件语言来描述cpu,最后还有在这种cpu支持的汇编指令,在有Tcl/Tk的环境下还带有图形界面,非常直观,可以在http://csapp.cs.cmu.edu/public/students.html里的Chapter 4rocessor Architecture中找到源代码。

3)设计一个汇编语言级别的虚拟机的要求
学习过计算机原理的人都知道,一个cpu至少需要有以下几个部件:a)内存,装载所要执行的指令之用;b)寄存器;3)指令集,没有指令集执行指令就无从谈起。前两者非常简单,无非就是在内存中分配一个空间来模拟就可以了,而后者这
里要专门说明一下。我们知道任何高级语言,经过这个高级语言的编译器编译之后都是翻译成汇编语言的,然后由汇编器汇编成二进制文件最后再进行库的链接等等才形成了可执行文件,而可执行文件最终也是二进制格式的,在执行可执行文件的时候由加载器加载到内存中去,那么这里就有一个问题了:cpu是如何识别已经加载到内存中二进制文件并且正确执行的?这需要下
面的一个概念:OpCode。
    OpCode是什么?简而言之,OpCode就是与汇编指令相对应的二进制格式的代码,OpCode的英文名是OperationCode(中文可以翻译成“操作码”),每一个汇编指令都有一个相对应的OpCode格式,反之不然,不过这个问题这里不再深究,只需要知道汇编器把汇编指令翻译成相应的由opcode组成的二进制文件,这样在可执行文件加载到内存的时候,cpu就可以根据在可执行文件中的opcode来执行程序了。理论上来说,不同厂家的cpu所支持的opcode是不同的,那么这里就有一个问题了,比如说在Intel机子上编译成功的可执行文件到了AMD的机子上如何正确执行呢?如果没有猜错的是,每个cpu在实现的时候需要在cpu的上层加一个翻译指令的东东....具体的我不清楚,只是猜测而已,也许不对。扯了这么多,回到这里要实现的cpu上,因为只是简易的cpu,所以在opcode上也尽量的精简,在这两个虚拟机的实现中,都是采用了汇编指令和opcode一一对应的关系进行实现(记住我前面说过汇编指令和opcode在真正的cpu中并不是一一对应的!),这样简化了cpu的实现。关于opcode,网上
有一份不错的教程<<学习opcode>;>;:http://www.luocong.com/learningopcode.htm,遗憾的是作者从开始写这份教程一直到现在差不多两年时间过去了还没有完成,不过前面的文章对于理解opcode的基本概念已经足够了。opcode看起来好像很高深,其实它就在我们身边,在linux上有一个objdump的反汇编软件可以反汇编二进制文件,比如这样的一段反汇编的代码:

  1. 116: 89 e5 mov %esp,%ebp
复制代码

其中的116是指令地址,而89 e5就是指令mov %esp,%ebp 所对应的opcode。
    总结一下,设计一个汇编语言级别的虚拟机至少需要以下的部件:1)内存空间,用于存放机器指令之用。2)寄存器:用于保存程序运行的状态,暂存数据等等之用。3)汇编器,汇编器的功能就是把汇编指令翻译成cpu指定的机器指令,然后将指令装入虚拟机的内存之中。4)指令集,指令集包括了指令的助记符,也就是汇编语言中的指令,还需要有每个指令所对        应的机器指令也就是OpCode,助记符由汇编器处理翻译成为机器指令,最后在cpu执行的时候根据不同的机器指令来执行相关的操作。
    虽然这两个虚拟机的设计略有不同,但是由于都是模拟的汇编语言级别的cpu,所以工作过程大体都是一致的,把握这个运行的过程是正确掌握这两个源代码的关键所在!虚拟机运行的大体过程如下:首先由汇编起扫描汇编源文件,将汇编指令也就是机器指令的助记符翻译为机器指令,如果没有错误就把机器指令加载到内存之中,这时汇编器的任务就结束了;然后由虚拟机读取已经装载到内存中的机器指令,根据机器指令对应的操作来执行指令。
   ok,这里基本上把一些基本的概念解释完了,后面紧跟着就可以开始我们的虚拟机之旅了....

论坛徽章:
0
2 [报告]
发表于 2005-01-16 12:49 |只看该作者

虚拟机源码分析

怎么没了?

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
3 [报告]
发表于 2005-01-16 12:52 |只看该作者

虚拟机源码分析

好。

论坛徽章:
2
亥猪
日期:2014-03-19 16:36:35午马
日期:2014-11-23 23:48:46
4 [报告]
发表于 2005-01-16 13:03 |只看该作者

虚拟机源码分析

原创的吗?
友情挺一下。

论坛徽章:
0
5 [报告]
发表于 2005-01-16 13:21 |只看该作者

虚拟机源码分析

原帖由 "gvim" 发表:
原创的吗?
友情挺一下。


是原创的呀,刚刚去吃饭了,现在在赶制第一个虚拟机源码的分析文档中,稍等稍等...

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
6 [报告]
发表于 2005-01-16 23:38 |只看该作者

虚拟机源码分析

我认为最好把它们放在一起,
给你加一个原创,你说呢?

论坛徽章:
0
7 [报告]
发表于 2005-01-17 08:38 |只看该作者

虚拟机源码分析

ok,听从斑竹的意见,现在就移过来。

论坛徽章:
0
8 [报告]
发表于 2005-01-17 08:38 |只看该作者

虚拟机源码分析

第一个剖析对象是<<编译原理与实践>;>;中自带的TM虚拟机

1)cpu技术指标
TM虚拟机中由一个只读指令存储区,数据区和8个寄存器组成,其中最后一个寄存器是PC寄存器,也就是程序计数器,用来保存下一个指令的地址,在跳转中以及读取指令的时候要用到,如下:

  1. /* 只读指令存储区的大小 */
  2. #define   IADDR_SIZE  1024 /* increase for large programs */
  3. /* 数据区的大小 */
  4. #define   DADDR_SIZE  1024 /* increase for large programs */
  5. /* 寄存器的数目 */
  6. #define   NO_REGS 8
  7. /* PC寄存器(程序计数器)的下标 */
  8. #define   PC_REG  7
  9. 在内存中分配了三个数组来实现模拟这三个数据区:
  10. /* 只读指令存储区 */
  11. INSTRUCTION iMem [IADDR_SIZE];
  12. /* 数据存储区 */
  13. int dMem [DADDR_SIZE];
  14. /* 寄存器 */
  15. int reg [NO_REGS];
复制代码

所支持的指令集,为了简化cpu的实现,采用的是一个enum类型来存储指令的opcode,在这里opcode和汇编指令是一一对应的,而指令分为三种类型,分别是RR,RM,RA,其中的RM类型的指令需要对数据区进行读取,而另外两种只需要对寄存器进行读取就可以了,opcode的类型用一个enum OPCLASS来分别:

  1. typedef enum {
  2.          opclRR,     /* reg operands r,s,t */
  3.          opclRM,     /* reg r, mem d+s */
  4.          opclRA      /* reg r, int d+s */
  5. } OPCLASS;
复制代码


三种不同的opcode类型的opcode的格式是有区别的:

  1. 指令类型                指令的格式
  2. RR                      r,s,t
  3. RM                      r,d(s)
  4. RA                      r,d(s)
复制代码

说明一下,对于不同类型的汇编指令,必须与这种汇编指令的opcode格式严格对应,如RR指令的类型必须是r,s,t等等。RM和RA的指令格式稍微有一点区别,这里要根据输入的"d(s)"得到另外一个值a = d + reg,就是说d是偏移值,而s在这里是寄存器数组的下标,对于RM来说,得到的a是对应于数据内存区数组的下标,这个a不能小于0或者大于这个内存区的大小,否则就会报错,而对RA而言,这个a值就是存储到相应的寄存器中的值,寄存器的选择根据不同的指令而定。

下面是这个虚拟机的汇编指令对应的opcode的列表,右边的注释是每个不同的指令对应的动作,也就是要根据opcode中的数据所要进行的不同的处理:

  1. /* 虚拟机的汇编指令对应的OPCODE */
  2. typedef enum {
  3.          /* RR instructions */
  4.          opHALT,    /* RR     halt, operands are ignored */
  5.          opIN,      /* RR     read into reg(r); s and t are ignored */
  6.          opOUT,     /* RR     write from reg(r), s and t are ignored */
  7.          opADD,     /* RR     reg(r) = reg(s)+reg(t) */
  8.          opSUB,     /* RR     reg(r) = reg(s)-reg(t) */
  9.          opMUL,     /* RR     reg(r) = reg(s)*reg(t) */
  10.          opDIV,     /* RR     reg(r) = reg(s)/reg(t) */
  11.          opRRLim,   /* limit of RR opcodes */

  12.          /* RM instructions */
  13.          opLD,      /* RM     reg(r) = mem(d+reg(s)) */
  14.          opST,      /* RM     mem(d+reg(s)) = reg(r) */
  15.          opRMLim,   /* Limit of RM opcodes */

  16.          /* RA instructions */
  17.          opLDA,     /* RA     reg(r) = d+reg(s) */
  18.          opLDC,     /* RA     reg(r) = d ; reg(s) is ignored */
  19.          opJLT,     /* RA     if reg(r)<0 then reg(7) = d+reg(s) */
  20.          opJLE,     /* RA     if reg(r)<=0 then reg(7) = d+reg(s) */
  21.          opJGT,     /* RA     if reg(r)>;0 then reg(7) = d+reg(s) */
  22.          opJGE,     /* RA     if reg(r)>;=0 then reg(7) = d+reg(s) */
  23.          opJEQ,     /* RA     if reg(r)==0 then reg(7) = d+reg(s) */
  24.          opJNE,     /* RA     if reg(r)!=0 then reg(7) = d+reg(s) */
  25.          opRALim    /* Limit of RA opcodes */
  26. } OPCODE;
复制代码


不论是哪一种类型的指令,都必须在指令内存区中保存相应的信息,比如说访问的寄存器的位置,内存的位置等等,这些信息保存在下面的一个结构体变量中的:

  1. /* 存储指令的值,iop是OPCODE,剩下三个是r,s,t */
  2. typedef struct {
  3.          int iop;
  4.          int iarg1;
  5.          int iarg2;
  6.          int iarg3;
  7. } INSTRUCTION;
复制代码

其中的iop就是指令对应的opcode,与前面的enum OPCODE中的成员一一对应,剩下的三个变量就是opcode中的r,s,t变量。指令内存区都INSTRUCTION类型的。

另外,执行指令的时候还要有不同的结果,这里同样的使用一个enum STEPRESULT类型来识别不同的结果,需要说明的是在读取内存的时候如果指针大小小于0或者大于内存的大小就会报错,另外在执行除法指令的时候还有可能出现零除错误:

  1. /* 枚举执行结果 */
  2. typedef enum {
  3.          srOKAY,                                        /* 正确执行 */
  4.          srHALT,                                        /* 停止执行 */
  5.          srIMEM_ERR,                                /* IMEM错误 */
  6.          srDMEM_ERR,                                /* DMEM错误 */
  7.          srZERODIVIDE                                /* 零除错误 */
  8. } STEPRESULT;
复制代码


2)cpu的工作原理
代码的量不大,只有700行不到,核心的函数有下面几个:
a)int readInstructions (void)
这个函数负责读取代码文件,是逐行处理的,对于每一行的文件首先检查指令是否符合这个虚拟机的汇编指令的格式,然后分辩这个指令的类型,再根据这个指令的类型存储不同的指令中opcode里的数据,每读取完一行代码如果没有错误的话就把指令及相应的opcode存储到指令存储区中,就是INSTRUCTION iMem [IADDR_SIZE]数组中,当读取文件结束的时候,这个数组中就都是相应的指令了,而后面的存储区存放的是HALT指令。

b)int doCommand (void)
这个函数负责读取stdin中用户输入的命令行参数来执行不同的动作,相关的动作这里不再详述,这个函数会一直执行下去,一直到用户输入q时才退出,在主函数main中是这样调用这个函数的:

  1.          do
  2.                   done = ! doCommand ();
  3.          while (! done );
复制代码


c)STEPRESULT stepTM (void)
这个函数是根据指令内存区中的指令逐步执行程序的函数,其中设定的一个局部变量         INSTRUCTION currentinstruction  ;
负责存储当前的指令:

  1. /* 从PC寄存器中读取下一条指令地址 */
  2.          pc = reg[PC_REG] ;
  3.          /* 如果小于零或者大于IADDR_SIZE,就是超过指令内存大小,就返回srIMEM_ERR错误 */
  4.          if ( (pc < 0) || (pc >; IADDR_SIZE)  )
  5.                   return srIMEM_ERR ;
  6.          /* PC加一 */
  7.          reg[PC_REG] = pc + 1 ;
  8.          /* 从内存中根据PC地址值读取当前要执行的指令 */
  9.          currentinstruction = iMem[ pc ] ;
复制代码


每读取完一个指令,就根据指令的类型以及指令所定义的不同的动作来执行代码,比如说:

  1. /* 根据iop中存储的OPCODE来执行指令,每个case右边是指令的执行情况 */
  2.          switch ( currentinstruction.iop)
  3.          {
  4.          case opHALT :                                /* RR     halt, operands are ignored */
  5.                   printf("HALT: %1d,%1d,%1d\n",r,s,t);
  6.                   return srHALT ;
  7.                   /* break; */

  8.          case opIN :                                /* RR     read into reg(r); s and t are ignored */
  9.                   do{
  10.                            printf("Enter value for IN instruction: ") ;
  11.                            fflush (stdin);
  12.                            fflush (stdout);
  13.                            gets(in_Line);
  14.                            lineLen = strlen(in_Line) ;
  15.                            inCol = 0;
  16.                            ok = getNum();
  17.                            if ( ! ok )
  18.                                         printf ("Illegal value\n");
  19.                            else
  20.                                         reg[r] = num;
  21.                   } while (! ok);
  22.                   break;
复制代码


剩余的其它函数都是简单的辅助函数了,无非是一些跳过空格,跳过检查是否是特定字符,得到字符串以及得到数字等等之类的函数了。

3)汇编指令的格式
这个虚拟机能够识别的汇编指令有一定的格式,如下:
a)忽略空行
b)以“*”号开头的都是注释
c)任何其它行都必须以整数开头,这个整数用于指定代码的位置,任何指令后面的文字都被认为是注释而忽略掉。
至于支持的指令就是与opcode一一对应的,不再详述

4)虚拟机的使用方式
TM虚拟机只有一个文件,只需要简单的编译就可以了,下面提供一个与该虚拟机对应的汇编代码:

  1.   0:     LD  6,0(0)
  2.   1:     ST  0,0(0)
  3.   2:     IN  0,0,0
  4.   3:     ST  0,0(5)
  5.   4:    LDC  0,0(0)
  6.   5:     ST  0,0(6)
  7.   6:     LD  0,0(5)
  8.   7:     LD  1,0(6)
  9.   8:    SUB  0,1,0
  10.   9:    JLT  0,2(7)
  11. 10:    LDC  0,0(0)
  12. 11:    LDA  7,1(7)
  13. 12:    LDC  0,1(0)
  14. 14:    LDC  0,1(0)
  15. 15:     ST  0,1(5)
  16. 16:     LD  0,1(5)
  17. 17:     ST  0,0(6)
  18. 18:     LD  0,0(5)
  19. 19:     LD  1,0(6)
  20. 20:    MUL  0,1,0
  21. 21:     ST  0,1(5)
  22. 22:     LD  0,0(5)
  23. 23:     ST  0,0(6)
  24. 24:    LDC  0,1(0)
  25. 25:     LD  1,0(6)
  26. 26:    SUB  0,1,0
  27. 27:     ST  0,0(5)
  28. 28:     LD  0,0(5)
  29. 29:     ST  0,0(6)
  30. 30:    LDC  0,0(0)
  31. 31:     LD  1,0(6)
  32. 32:    SUB  0,1,0
  33. 33:    JEQ  0,2(7)
  34. 34:    LDC  0,0(0)
  35. 35:    LDA  7,1(7)
  36. 36:    LDC  0,1(0)
  37. 37:    JEQ  0,-22(7)
  38. 38:     LD  0,1(5)
  39. 39:    OUT  0,0,0
  40. 13:    JEQ  0,27(7)
  41. 40:    LDA  7,0(7)
  42. 41:   HALT  0,0,0
复制代码

假设编译好的虚拟机的可执行文件是TM,而汇编代码文件是1.tm(这个虚拟机默认的可识别的汇编文件是*.tm),那么只需要简单的使用:

  1. TM 1.tm
复制代码

就可以了。

ok,第一个虚拟机的分析到此,下面是完整的源代码:

论坛徽章:
0
9 [报告]
发表于 2005-01-17 08:39 |只看该作者

虚拟机源码分析


  1. /****************************************************/
  2. /* File: tm.c                                       */
  3. /* The TM ("Tiny Machine") computer                 */
  4. /* Compiler Construction: Principles and Practice   */
  5. /* Kenneth C. Louden                                */
  6. /****************************************************/

  7. #include <stdio.h>;
  8. #include <stdlib.h>;
  9. #include <string.h>;
  10. #include <ctype.h>;

  11. #ifndef TRUE
  12. #define TRUE 1
  13. #endif
  14. #ifndef FALSE
  15. #define FALSE 0
  16. #endif

  17. /******* const *******/
  18. /* 只读指令存储区的大小 */
  19. #define   IADDR_SIZE  1024 /* increase for large programs */
  20. /* 数据区的大小 */
  21. #define   DADDR_SIZE  1024 /* increase for large programs */
  22. /* 寄存器的数目 */
  23. #define   NO_REGS 8
  24. /* PC寄存器(程序计数器)的下标 */
  25. #define   PC_REG  7

  26. #define   LINESIZE  121
  27. #define   WORDSIZE  20

  28. /******* type  *******/

  29. /* 虚拟机的指令类型,有三种 */
  30. typedef enum {
  31.          opclRR,     /* reg operands r,s,t */
  32.          opclRM,     /* reg r, mem d+s */
  33.          opclRA      /* reg r, int d+s */
  34. } OPCLASS;

  35. /* 虚拟机的汇编指令对应的OPCODE */
  36. typedef enum {
  37.          /* RR instructions */
  38.          opHALT,    /* RR     halt, operands are ignored */
  39.          opIN,      /* RR     read into reg(r); s and t are ignored */
  40.          opOUT,     /* RR     write from reg(r), s and t are ignored */
  41.          opADD,     /* RR     reg(r) = reg(s)+reg(t) */
  42.          opSUB,     /* RR     reg(r) = reg(s)-reg(t) */
  43.          opMUL,     /* RR     reg(r) = reg(s)*reg(t) */
  44.          opDIV,     /* RR     reg(r) = reg(s)/reg(t) */
  45.          opRRLim,   /* limit of RR opcodes */

  46.          /* RM instructions */
  47.          opLD,      /* RM     reg(r) = mem(d+reg(s)) */
  48.          opST,      /* RM     mem(d+reg(s)) = reg(r) */
  49.          opRMLim,   /* Limit of RM opcodes */

  50.          /* RA instructions */
  51.          opLDA,     /* RA     reg(r) = d+reg(s) */
  52.          opLDC,     /* RA     reg(r) = d ; reg(s) is ignored */
  53.          opJLT,     /* RA     if reg(r)<0 then reg(7) = d+reg(s) */
  54.          opJLE,     /* RA     if reg(r)<=0 then reg(7) = d+reg(s) */
  55.          opJGT,     /* RA     if reg(r)>;0 then reg(7) = d+reg(s) */
  56.          opJGE,     /* RA     if reg(r)>;=0 then reg(7) = d+reg(s) */
  57.          opJEQ,     /* RA     if reg(r)==0 then reg(7) = d+reg(s) */
  58.          opJNE,     /* RA     if reg(r)!=0 then reg(7) = d+reg(s) */
  59.          opRALim    /* Limit of RA opcodes */
  60. } OPCODE;

  61. /* 枚举执行结果 */
  62. typedef enum {
  63.          srOKAY,                                        /* 正确执行 */
  64.          srHALT,                                        /* 停止执行 */
  65.          srIMEM_ERR,                                /* IMEM错误 */
  66.          srDMEM_ERR,                                /* DMEM错误 */
  67.          srZERODIVIDE                                /* 零除错误 */
  68. } STEPRESULT;

  69. /* 存储指令的值,iop是OPCODE,剩下三个是r,s,t */
  70. typedef struct {
  71.          int iop;
  72.          int iarg1;
  73.          int iarg2;
  74.          int iarg3;
  75. } INSTRUCTION;

  76. /******** vars ********/
  77. /* 指向只读指令存储区的指针 */
  78. int iloc = 0 ;
  79. /* 指向数据存储区的指针 */
  80. int dloc = 0 ;
  81. /* 是否跟踪程序执行情况 */
  82. int traceflag = FALSE;
  83. /* 是否需要打印出执行的指令数量 */
  84. int icountflag = FALSE;

  85. /* 只读指令存储区 */
  86. INSTRUCTION iMem [IADDR_SIZE];
  87. /* 数据存储区 */
  88. int dMem [DADDR_SIZE];
  89. /* 寄存器 */
  90. int reg [NO_REGS];

  91. /* 指令列表,用于在stdout上打印出程序执行情况之用,与enum OPCODE对应,其中的"????"则与相应的LIM值对应,无意义 */
  92. char *opCodeTab[] = {
  93.          /* RR opcodes */
  94.          "HALT","IN","OUT","ADD","SUB","MUL","DIV","????",
  95.      /* RM opcodes */
  96.          "LD","ST","????",
  97.          /* RA opcodes */
  98.          "LDA","LDC","JLT","JLE","JGT","JGE","JEQ","JNE","????"
  99. };

  100. /* 程序结果列表,用于在stdout上打印出程序执行情况之用,与enum STEPRESULT对应 */
  101. char * stepResultTab[] =
  102. {
  103.          "OK",
  104.          "Halted",
  105.          "Instruction Memory Fault",
  106.          "Data Memory Fault",
  107.          "Division by 0"
  108. };

  109. /* 存储文件名 */
  110. char pgmName[20];
  111. /* 代码文件的FILE指针 */
  112. FILE *pgm  ;

  113. /* 文件的每一行都存在这个数组里 */
  114. char in_Line[LINESIZE] ;
  115. /* 读取到当前文件的行数记录 */
  116. int lineLen;
  117. /* in_Line数组中的下标 */
  118. int inCol;
  119. /* 存储getNum()函数的结果 */
  120. int num  ;
  121. /* 存储getWord()函数的结果 */
  122. char word[WORDSIZE] ;
  123. /* 存储getCh()函数的结果 */
  124. char ch  ;
  125. /* 存储docomand()函数的执行结果,用于表示程序是否结束 */
  126. int done  ;

  127. /*************************************************************************************
  128. * int opClass( int c ):根据c的值在OPCODE枚举型中查找指令的类型,有RR,RM,RA三种指令
  129. *************************************************************************************/
  130. int opClass( int c )
  131. {
  132.          if ( c <= opRRLim)
  133.                   return ( opclRR );
  134.          else if ( c <= opRMLim)
  135.                   return ( opclRM );
  136.          else
  137.                   return ( opclRA );
  138. } /* opClass */

  139. /**************************************************************************************
  140. *void writeInstruction ( int loc ):向stdout上打印出程序的执行情况
  141. **************************************************************************************/
  142. void writeInstruction ( int loc )
  143. {
  144.          printf( "%5d: ", loc) ;
  145.          if ( (loc >;= 0) && (loc < IADDR_SIZE) )
  146.          {
  147.                   printf("%6s%3d,", opCodeTab[iMem[loc].iop], iMem[loc].iarg1);
  148.                   switch ( opClass(iMem[loc].iop) )
  149.                   {
  150.                   case opclRR:
  151.                            printf("%1d,%1d", iMem[loc].iarg2, iMem[loc].iarg3);
  152.                            break;
  153.                   case opclRM:
  154.                   case opclRA:
  155.                            printf("%3d(%1d)", iMem[loc].iarg2, iMem[loc].iarg3);
  156.                            break;
  157.                   }
  158.                   printf ("\n") ;
  159.          }
  160. } /* writeInstruction */

  161. /*************************************************************************************
  162. * void getCh (void):在in_line数组中读取字符,如果到文件尾,就返回空字符,并且将结果存入ch中
  163. **************************************************************************************/
  164. void getCh (void)
  165. {
  166.          if (++inCol < lineLen)
  167.                   ch = in_Line[inCol] ;
  168.          else ch = ' ' ;
  169. } /* getCh */

  170. /**************************************************************************************
  171. * int nonBlank (void): 查找某行文件后面是否都是空格,如果是则设置ch=' '并且返回false,
  172. *                      否则设置ch为第一个非空字符返回true
  173. ***************************************************************************************/
  174. int nonBlank (void)
  175. {
  176.          while ((inCol < lineLen)
  177.                         && (in_Line[inCol] == ' ') )
  178.                   inCol++ ;
  179.          if (inCol < lineLen)
  180.          {
  181.                   ch = in_Line[inCol] ;
  182.                   return TRUE ;
  183.          }
  184.          else
  185.          {
  186.                   ch = ' ' ;
  187.                   return FALSE ;
  188.          }
  189. } /* nonBlank */

  190. /***************************************************************************************
  191. * int getNum (void):判断字符是否是数字,不是就返回false,否则返回true并且num中存储读入的数字
  192. ****************************************************************************************/
  193. int getNum (void)
  194. {
  195.          int sign;
  196.          int term;
  197.          int temp = FALSE;
  198.          num = 0 ;

  199.          do {
  200.                   sign = 1;
  201.                   while ( nonBlank() && ((ch == '+') || (ch == '-')) )
  202.                   {
  203.                            temp = FALSE ;
  204.                            if (ch == '-')  
  205.                                         sign = - sign ;
  206.                            getCh();
  207.                   }
  208.                   term = 0 ;
  209.                   nonBlank();
  210.                   while (isdigit(ch))
  211.                   {
  212.                            temp = TRUE ;
  213.                            term = term * 10 + ( ch - '0' ) ;
  214.                            getCh();
  215.                   }
  216.                   num = num + (term * sign) ;
  217.          } while ( (nonBlank()) && ((ch == '+') || (ch == '-')) ) ;

  218.          return temp;
  219. } /* getNum */

  220. /****************************************************************************************
  221. *int getWord (void):判断后面紧接着的是否是符号,就是以字母或者数字开头的符号,是就返回true
  222. *                   并且将该符号存入word数组之中,否则返回false
  223. ****************************************************************************************/
  224. int getWord (void)
  225. {
  226.          int temp = FALSE;
  227.          int length = 0;
  228.          if (nonBlank ())
  229.          {
  230.                   while (isalnum(ch))
  231.                   {
  232.                            if (length < WORDSIZE-1)
  233.                                         word [length++] =  ch ;
  234.                            getCh() ;
  235.                   }
  236.                   word[length] = '\0';
  237.                   temp = (length != 0);
  238.          }

  239.          return temp;
  240. } /* getWord */

  241. /*****************************************************************************************  
  242. *int skipCh ( char c  ):略过指定的字符,如果找不到这个字符那么返回false,否则返回true
  243. *****************************************************************************************/
  244. int skipCh ( char c  )
  245. {
  246.          int temp = FALSE;
  247.          if ( nonBlank() && (ch == c) )
  248.          {
  249.                   getCh();
  250.                   temp = TRUE;
  251.          }
  252.          return temp;
  253. } /* skipCh */

  254. /******************************************************************************************   
  255. *int atEOL(void):是否到达行尾,是就返回非零值,否则返回零值
  256. ******************************************************************************************/
  257. int atEOL(void)
  258. {
  259.          return ( ! nonBlank ());
  260. } /* atEOL */

  261. /*******************************************************************************************   
  262. * int error( char * msg, int lineNo, int instNo):打印出错信息,其中msg是出错信息,
  263. *                                                lineNo是行数,instNo是指令数
  264. *******************************************************************************************/
  265. int error( char * msg, int lineNo, int instNo)
  266. {
  267.          printf("Line %d",lineNo);
  268.          if (instNo >;= 0)
  269.                   printf(" (Instruction %d)",instNo);
  270.          printf("   %s\n",msg);
  271.          return FALSE;
  272. } /* error */

  273. /*******************************************************************************************   
  274. * int readInstructions (void):读取代码文件进行处理
  275. *******************************************************************************************/
  276. int readInstructions (void)
  277. {
  278.          /* op存储指令 */
  279.          OPCODE op;
  280.          /* 存储r,s,t */
  281.          int arg1, arg2, arg3;
  282.          /* loc是指令的位置, regNO是寄存器的位置,lineNO是代码中的行数 */
  283.          int loc, regNo, lineNo;

  284.          /* 清空寄存器 */
  285.          for (regNo = 0 ; regNo < NO_REGS ; regNo++)
  286.                   reg[regNo] = 0 ;
  287.          /* 不明白为什么这样做? */
  288.          dMem[0] = DADDR_SIZE - 1 ;
  289.          /* 清空数据区 */
  290.          for (loc = 1 ; loc < DADDR_SIZE ; loc++)
  291.                   dMem[loc] = 0 ;
  292.          /* 初始化指令存储区的OPCODE是opHALT */
  293.          for (loc = 0 ; loc < IADDR_SIZE ; loc++)
  294.          {
  295.                   iMem[loc].iop = opHALT ;
  296.                   iMem[loc].iarg1 = 0 ;
  297.                   iMem[loc].iarg2 = 0 ;
  298.                   iMem[loc].iarg3 = 0 ;
  299.          }
  300.          /* 初始化行数为0 */
  301.          lineNo = 0 ;
  302.          while (! feof(pgm))                /* 对文件进行逐行的读取操作,然后对每一行代码进行处理 */
  303.          {
  304.                   /* 读入一行代码 */
  305.                   fgets( in_Line, LINESIZE-2, pgm  ) ;
  306.                   /* 设置行的列号为0 */
  307.                   inCol = 0 ;
  308.                   /* 行数加一 */
  309.                   lineNo++;
  310.                   lineLen = strlen(in_Line)-1 ;
  311.                   /* 把行尾置为'\0',方便字符串操作 */
  312.                   if (in_Line[lineLen]=='\n')
  313.                            in_Line[lineLen] = '\0' ;
  314.                   else
  315.                            in_Line[++lineLen] = '\0';
  316.                   /* 如果指令不是空格或者注释 */
  317.                   if ( (nonBlank()) && (in_Line[inCol] != '*') )
  318.                   {
  319.                            /* 如果不是数字,就显示错误,因为指令都是以数字开始 */
  320.                            if (! getNum())
  321.                                         return error("Bad location", lineNo,-1);
  322.                            /* 存储指令的位置 */
  323.                            loc = num;
  324.                            /* 大于指令存储区的大小 */
  325.                            if (loc >; IADDR_SIZE)
  326.                                         return error("Location too large",lineNo,loc);
  327.                            /* 如果后面没有紧接着':',则显示出错 */
  328.                            if (! skipCh(':'))
  329.                                         return error("Missing colon", lineNo,loc);
  330.                            /* 如果后面紧接着的不是符号,则显示出错 */
  331.                            if (! getWord ())
  332.                                         return error("Missing opcode", lineNo,loc);
  333.                            /* 初始化为HALT指令 */
  334.                            op = opHALT ;
  335.                            /* 循环查找word指令对应的OPCODE,op就是在opCodeTab中对应的指令的下标 */
  336.                            while ((op < opRALim)
  337.                                           && (strncmp(opCodeTab[op], word, 4) != 0) )
  338.                                         op++ ;
  339.                            /* 没有找到对应的OPCODE,显示出错 */
  340.                            if (strncmp(opCodeTab[op], word, 4) != 0)
  341.                                         return error("Illegal opcode", lineNo,loc);
  342.                           
  343.                            /* 调用opClass函数对指令进行分类,不同的指令处理不相同 */
  344.                            switch ( opClass(op) )
  345.                            {
  346.                            case opclRR :        /* 处理RR指令,具体为什么会如下处理可以查看RR指令的格式 */
  347.                                         /* 如果后面紧接着的不是数字或者数字是非法的就显示出错 */
  348.                                         if ( (! getNum ()) || (num < 0) || (num >;= NO_REGS) )
  349.                                                  return error("Bad first register", lineNo,loc);
  350.                                         arg1 = num;
  351.                                         /* 如果后面没有紧跟着',',就显示出错 */
  352.                                         if ( ! skipCh(','))
  353.                                                  return error("Missing comma", lineNo, loc);
  354.                     /* 如果后面紧接着的不是数字或者数字是非法的就显示出错 */
  355.                                         if ( (! getNum ()) || (num < 0) || (num >;= NO_REGS) )
  356.                                                  return error("Bad second register", lineNo, loc);
  357.                                         arg2 = num;
  358.                                         /* 如果后面没有紧跟着',',就显示出错 */
  359.                                         if ( ! skipCh(','))
  360.                                                  return error("Missing comma", lineNo,loc);
  361.                                         /* 如果后面紧接着的不是数字或者数字对于RR命令是非法的就显示出错 */
  362.                                         if ( (! getNum ()) || (num < 0) || (num >;= NO_REGS) )
  363.                                                  return error("Bad third register", lineNo,loc);
  364.                                         arg3 = num;
  365.                                         break;

  366.                            case opclRM :        /* 处理RM指令,具体为什么会如下处理可以查看RM指令的格式 */
  367.                            case opclRA :        /* 处理RA指令,具体为什么会如下处理可以查看RA指令的格式 */
  368.                                         /* 如果后面紧接着的不是数字或者数字是非法的就显示出错 */
  369.                                         if ( (! getNum ()) || (num < 0) || (num >;= NO_REGS) )
  370.                                                  return error("Bad first register", lineNo,loc);
  371.                                         arg1 = num;
  372.                                         /* 如果后面没有紧跟着','就显示出错 */
  373.                                         if ( ! skipCh(','))
  374.                                                  return error("Missing comma", lineNo,loc);
  375.                                         /* 如果后面没有紧跟着数字就显示出错 */
  376.                                         if (! getNum ())
  377.                                                  return error("Bad displacement", lineNo,loc);
  378.                                         arg2 = num;
  379.                                         /* 如果后面没有紧跟着'('或者是','就显示出错 */
  380.                                         if ( ! skipCh('(') && ! skipCh(',') )
  381.                                                  return error("Missing LParen", lineNo,loc);
  382.                                         /* 如果紧跟的不是数字或者数字是非法的就显示出错 */
  383.                                         if ( (! getNum ()) || (num < 0) || (num >;= NO_REGS))
  384.                                                  return error("Bad second register", lineNo,loc);
  385.                                         arg3 = num;
  386.                                         break;
  387.                            } /* switch ( opClass(op) ) */
  388.                            /* OK,读取一行代码结束,把指令存入指令存储区 */
  389.                            iMem[loc].iop = op;
  390.                            iMem[loc].iarg1 = arg1;
  391.                            iMem[loc].iarg2 = arg2;
  392.                            iMem[loc].iarg3 = arg3;
  393.                   }        /* if ( (nonBlank()) && (in_Line[inCol] != '*') ) */
  394.          }                /* while (! feof(pgm)) */

  395.          return TRUE;
  396. } /* readInstructions */

  397. /********************************************************************************************
  398. * STEPRESULT stepTM (void):根据指令内存区中的存储的指令逐步执行指令,并且返回执行结果
  399. ********************************************************************************************/
  400. STEPRESULT stepTM (void)
  401. {
  402.          INSTRUCTION currentinstruction  ;
  403.          int pc  ;
  404.          int r,s,t,m  ;
  405.          int ok ;

  406.          /* 从PC寄存器中读取下一条指令地址 */
  407.          pc = reg[PC_REG] ;
  408.          /* 如果小于零或者大于IADDR_SIZE,就是超过指令内存大小,就返回srIMEM_ERR错误 */
  409.          if ( (pc < 0) || (pc >; IADDR_SIZE)  )
  410.                   return srIMEM_ERR ;
  411.          /* PC加一 */
  412.          reg[PC_REG] = pc + 1 ;
  413.          /* 从内存中根据PC地址值读取当前要执行的指令 */
  414.          currentinstruction = iMem[ pc ] ;
  415.          
  416.      /*  调用opClass函数确定opcode的类型 */
  417.          switch (opClass(currentinstruction.iop) )
  418.          {
  419.          case opclRR :                                /* 对于RR指令而言,opcode格式是opcode r, s, t */
  420.                   r = currentinstruction.iarg1 ;
  421.                   s = currentinstruction.iarg2 ;
  422.                   t = currentinstruction.iarg3 ;
  423.                   break;
  424.                   
  425.          case opclRM :                                 /* 对于RM指令而言,opcode格式是opcode r, d(s),而m = d + reg(s) */
  426.                   r = currentinstruction.iarg1 ;
  427.                   s = currentinstruction.iarg3 ;
  428.                   /* 对应RM指令中的m = d + reg[s],相当于变址寻址,这个地址用于访问数据区 */
  429.                   m = currentinstruction.iarg2 + reg[s] ;
  430.                   /* 如果地址是非法的(对于数据存储区而言),就返回一个srDMEM_ERR错误 */
  431.                   if ( (m < 0) || (m >; DADDR_SIZE))
  432.                            return srDMEM_ERR ;
  433.                   break;

  434.          case opclRA :                                /* 对于RA指令而言,opcode格式是opcode r, d(s),而m = d + reg(s),m值最后存入相应的寄存器 */
  435.                   r = currentinstruction.iarg1 ;
  436.                   s = currentinstruction.iarg3 ;
  437.                   m = currentinstruction.iarg2 + reg[s] ;
  438.                   break;
  439.          } /* case */

  440.          /* 根据iop中存储的OPCODE来执行指令,每个case右边是指令的执行情况 */
  441.          switch ( currentinstruction.iop)
  442.          {
  443.          case opHALT :                                /* RR     halt, operands are ignored */
  444.                   printf("HALT: %1d,%1d,%1d\n",r,s,t);
  445.                   return srHALT ;
  446.                   /* break; */

  447.          case opIN :                                /* RR     read into reg(r); s and t are ignored */
  448.                   do{
  449.                            printf("Enter value for IN instruction: ") ;
  450.                            fflush (stdin);
  451.                            fflush (stdout);
  452.                            gets(in_Line);
  453.                            lineLen = strlen(in_Line) ;
  454.                            inCol = 0;
  455.                            ok = getNum();
  456.                            if ( ! ok )
  457.                                         printf ("Illegal value\n");
  458.                            else
  459.                                         reg[r] = num;
  460.                   } while (! ok);
  461.                   break;

  462.          case opOUT :                                  /* RR     write from reg(r), s and t are ignored */
  463.                   printf ("OUT instruction prints: %d\n", reg[r] ) ;
  464.                   break;
  465.          case opADD :                                  /* RR     reg(r) = reg(s)+reg(t) */
  466.                   reg[r] = reg[s] + reg[t] ;  
  467.                   break;
  468.          case opSUB :                                  /* RR     reg(r) = reg(s)-reg(t) */
  469.                   reg[r] = reg[s] - reg[t] ;  
  470.                   break;
  471.          case opMUL :                                  /* RR     reg(r) = reg(s)*reg(t) */
  472.                   reg[r] = reg[s] * reg[t] ;  
  473.                   break;

  474.          case opDIV :                                /* RR     reg(r) = reg(s)/reg(t) */
  475.                   if ( reg[t] != 0 )
  476.                            reg[r] = reg[s] / reg[t];
  477.                   else
  478.                            return srZERODIVIDE ;
  479.                   break;

  480.      /*************** RM instructions ********************/
  481.          case opLD :                            /* RM     reg(r) = mem(d+reg(s)) */
  482.                   reg[r] = dMem[m] ;  
  483.                   break;
  484.          case opST :                            /* RM     mem(d+reg(s)) = reg(r) */
  485.                   dMem[m] = reg[r] ;  
  486.                   break;

  487.          /*************** RA instructions ********************/
  488.          case opLDA :                            /* RA     reg(r) = d+reg(s) */
  489.                   reg[r] = m ;
  490.                   break;
  491.          case opLDC :                            /* RA     reg(r) = d ; reg(s) is ignored */
  492.                   reg[r] = currentinstruction.iarg2 ;   
  493.                   break;
  494.          case opJLT :                            /* RA     if reg(r)<0 then reg(7) = d+reg(s) */
  495.                   if ( reg[r] <  0 )
  496.                            reg[PC_REG] = m ;
  497.                   break;
  498.          case opJLE :                            /* RA     if reg(r)<=0 then reg(7) = d+reg(s) */
  499.                   if ( reg[r] <=  0 )
  500.                            reg[PC_REG] = m ;
  501.                   break;
  502.          case opJGT :                            /* RA     if reg(r)>;0 then reg(7) = d+reg(s) */
  503.                   if ( reg[r] >;  0 )
  504.                            reg[PC_REG] = m ;
  505.                   break;
  506.          case opJGE :                            /* RA     if reg(r)>;=0 then reg(7) = d+reg(s) */
  507.                   if ( reg[r] >;=  0 )
  508.                            reg[PC_REG] = m ;
  509.                   break;
  510.          case opJEQ :                            /* RA     if reg(r)==0 then reg(7) = d+reg(s) */
  511.                   if ( reg[r] == 0 )
  512.                            reg[PC_REG] = m ;
  513.                   break;
  514.          case opJNE :                            /* RA     if reg(r)!=0 then reg(7) = d+reg(s) */
  515.                   if ( reg[r] != 0 )
  516.                            reg[PC_REG] = m ;
  517.                   break;

  518.                   /* end of legal instructions */
  519.          } /* case */
  520.          
  521.      /* 如果程序能够正常执行到这里,就返回执行正确的信息 */
  522.          return srOKAY ;
  523. } /* stepTM */

  524. /********************************************************************************************
  525. *int doCommand (void):执行指令
  526. * *******************************************************************************************/
  527. int doCommand (void)
  528. {
  529.          char cmd;
  530.          int stepcnt=0, i;
  531.          int printcnt;
  532.          int stepResult;
  533.          int regNo, loc;

  534.          do {                                                 /* 读入执行虚拟机的命令行参数 */
  535.                   printf ("Enter command: ");
  536.                   fflush (stdin);
  537.                   fflush (stdout);
  538.                   gets(in_Line);
  539.                   lineLen = strlen(in_Line);
  540.                   inCol = 0;
  541.          } while (! getWord ());

  542.          cmd = word[0] ;
  543.          switch ( cmd )
  544.          {
  545.          case 't' :                                        /* 是否跟踪调试 */
  546.                   traceflag = ! traceflag ;
  547.                   printf("Tracing now ");
  548.                   if ( traceflag )
  549.                            printf("on.\n");
  550.                   else
  551.                            printf("off.\n");
  552.                   break;

  553.          case 'h' :                                        /* 打印出命令及相应功能列表 */
  554.                   printf("Commands are:\n");
  555.                   printf("   s(tep <n>;      "\
  556.                                  "Execute n (default 1) TM instructions\n");
  557.                   printf("   g(o            "\
  558.                                  "Execute TM instructions until HALT\n");
  559.                   printf("   r(egs          "\
  560.                                  "Print the contents of the registers\n");
  561.                   printf("   i(Mem <b <n>;>;  "\
  562.                                  "Print n iMem locations starting at b\n");
  563.                   printf("   d(Mem <b <n>;>;  "\
  564.                                  "Print n dMem locations starting at b\n");
  565.                   printf("   t(race         "\
  566.                                  "Toggle instruction trace\n");
  567.                   printf("   p(rint         "\
  568.                                  "Toggle print of total instructions executed"\
  569.                                  " ('go' only)\n");
  570.                   printf("   c(lear         "\
  571.                                  "Reset simulator for new execution of program\n");
  572.                   printf("   h(elp          "\
  573.                                  "Cause this list of commands to be printed\n");
  574.                   printf("   q(uit          "\
  575.                                  "Terminate the simulation\n");
  576.                   break;

  577.          case 'p' :                                        /* 是否打印出执行的指令的步数 */
  578.                   icountflag = ! icountflag ;
  579.                   printf("Printing instruction count now ");
  580.                   if ( icountflag )
  581.                            printf("on.\n");
  582.                   else
  583.                            printf("off.\n");
  584.                   break;

  585.          case 's' :                                        /* 指定执行的步数 */
  586.                   if ( atEOL ())  
  587.                            stepcnt = 1;
  588.                   else if ( getNum ())  
  589.                            stepcnt = abs(num);
  590.                   else
  591.                            printf("Step count?\n");
  592.                   break;

  593.          case 'g' :                                   /* 执行指令一直到HALT */
  594.                   stepcnt = 1 ;     
  595.                   break;

  596.          case 'r' :                                        /* 打印出寄存器中的内容 */
  597.                   for (i = 0; i < NO_REGS; i++)
  598.                   {
  599.                            printf("%1d: %4d    ", i,reg[i]);
  600.                            if ( (i % 4) == 3 )
  601.                                         printf ("\n");
  602.                   }
  603.                   break;

  604.          case 'i' :                                        /* 打印出只读指令存储区的内容(指令),也可以自己指定存储区的位置 */
  605.                   printcnt = 1 ;
  606.                   /* printcnt用于计数,计算总共要打印出多少行的内容,而iloc是指向这一段内存的指针 */
  607.                   if ( getNum ())
  608.                   {
  609.                            iloc = num ;
  610.                            if ( getNum ())
  611.                                         printcnt = num ;
  612.                   }
  613.                   if ( ! atEOL ())
  614.                            printf ("Instruction locations?\n");
  615.                   else
  616.                   {
  617.                            while ((iloc >;= 0) && (iloc < IADDR_SIZE)
  618.                                           && (printcnt >; 0) )
  619.                            {
  620.                                         writeInstruction(iloc);
  621.                                         iloc++ ;
  622.                                         printcnt-- ;
  623.                            }
  624.                   }
  625.                   break;

  626.          case 'd' :                                        /* 打印出数据存储区的内容(指令),也可以自己指定存储区的位置 */
  627.                   printcnt = 1 ;
  628.                   /* printcnt用于计数,计算总共要打印出多少行的内容,而dloc是指向这一段内存的指针 */
  629.                   if ( getNum  ())
  630.                   {
  631.                            dloc = num ;
  632.                            if ( getNum ())
  633.                                         printcnt = num ;
  634.                   }
  635.                   if ( ! atEOL ())               
  636.                            printf("Data locations?\n");
  637.                   else
  638.                   {
  639.                            while ((dloc >;= 0) && (dloc < DADDR_SIZE)
  640.                                           && (printcnt >; 0))
  641.                            {
  642.                                         printf("%5d: %5d\n",dloc,dMem[dloc]);
  643.                                         dloc++;
  644.                                         printcnt--;
  645.                            }
  646.                   }
  647.                   break;

  648.          case 'c' :                                        /* 清空虚拟机所有状态 */
  649.                   iloc = 0;
  650.                   dloc = 0;
  651.                   stepcnt = 0;
  652.                   for (regNo = 0;  regNo < NO_REGS ; regNo++)
  653.                            reg[regNo] = 0 ;
  654.                   dMem[0] = DADDR_SIZE - 1 ;
  655.                   for (loc = 1 ; loc < DADDR_SIZE ; loc++)
  656.                            dMem[loc] = 0 ;
  657.                   break;

  658.          case 'q' :                                 /* 退出 */
  659.                   return FALSE;  

  660.          default :                                         /* 未知命令 */
  661.                   printf("Command %c unknown.\n", cmd);
  662.                   break;
  663.          }  /* case */
  664.          stepResult = srOKAY;
  665.          if ( stepcnt >; 0 )
  666.          {
  667.                   if ( cmd == 'g' )
  668.                   {
  669.                            stepcnt = 0;
  670.                            /* 当命令行参数是g的时候,就一直执行程序 */
  671.                            while (stepResult == srOKAY)
  672.                            {
  673.                                         iloc = reg[PC_REG] ;
  674.                                         /* 如果设置了跟踪标志,那么在stdout上打印出执行的指令 */
  675.                                         if ( traceflag )
  676.                                                  writeInstruction( iloc ) ;
  677.                                         stepResult = stepTM ();
  678.                                         stepcnt++;
  679.                            }
  680.                            /* 打印出执行的指令数量 */
  681.                            if ( icountflag )
  682.                                         printf("Number of instructions executed = %d\n",stepcnt);
  683.                   }
  684.                   else                                        /* 否则根据stepResult中指定的步长执行指令 */
  685.                   {
  686.                            while ((stepcnt >; 0) && (stepResult == srOKAY))
  687.                            {
  688.                                         iloc = reg[PC_REG] ;
  689.                                         if ( traceflag )
  690.                                                  writeInstruction( iloc ) ;
  691.                                         stepResult = stepTM ();
  692.                                         stepcnt-- ;
  693.                            }
  694.                   }
  695.                   printf( "%s\n",stepResultTab[stepResult] );
  696.          }
  697.          return TRUE;
  698. } /* doCommand */

  699. /********************************************************************************************
  700. *int main( int argc, char * argv[] ):主函数
  701. ********************************************************************************************/
  702. int main( int argc, char * argv[] )
  703. {
  704.          if (argc != 2)
  705.          { printf("usage: %s <filename>;\n",argv[0]);
  706.                   exit(1);
  707.          }
  708.          strcpy(pgmName,argv[1]) ;
  709.          if (strchr (pgmName, '.') == NULL)
  710.                   strcat(pgmName,".tm");
  711.          pgm = fopen(pgmName,"r");
  712.          if (pgm == NULL)
  713.          { printf("file '%s' not found\n",pgmName);
  714.                   exit(1);
  715.          }

  716.          /* read the program */
  717.          if ( ! readInstructions ())
  718.                   exit(1) ;
  719.          /* switch input file to terminal */
  720.          /* reset( input ); */
  721.          /* read-eval-print */
  722.          printf("TM  simulation (enter h for help)...\n");
  723.          do
  724.                   done = ! doCommand ();
  725.          while (! done );
  726.          printf("Simulation done.\n");

  727.          return 0;
  728. }

复制代码

论坛徽章:
0
10 [报告]
发表于 2005-01-17 10:20 |只看该作者

虚拟机源码分析

学习
混一贴先
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP