在linux环境下编写汇编

 最近在学习微机原理,会学汇编,但是学校上的课程显然是在Windows平台上的,可自己还是想在linux上干这些事,而且自己还是挺想坚持以前的“一个操作系统的实现”的计划,但是由于汇编和各种可编程逻辑器件不是很明白,正好这学期开来微机原理,想提高自己的能力,所以多花点时间在汇编上吧,凡事入门都还是挺不容易的,今天开个头吧,看了这样一片文档:

http://docs.cs.up.ac.za/programming/asm/derick_tut/quickstart.html

收获剖多,而且对比了linux和dos编写在屏幕显示helloworld这个最简单程序的不同,一下是自己觉得很好的几句话吧:

1.Linux is a 32-bitprotected mode operating system, and in 32-bit assembly there are no memory models. Also, allsegment registers and paging have already been set up to give you the same 32-bit 4Gb address space,so you can ignore all segment registers. It is also not necessary to specify the stack size.

2.Linux NASM allows us to declare constants with the EQU instruction, for example:
bufferlen: equ 400
So whenever it sees bufferlen in your program, it will substitute the value '400'. Thatmeans you don't have to put square brackets aroundbufferlen to get its actual value.(Note: this only works for constants. The values of all other variables are still obtained using[varname]).

3.In DOS, we call int 21h to use a DOS service like printing out a string. In Linux, you usesystem calls, which are accessed by callingint 80h (the kernel interrupt). In DOS the functionnumber (eg. 9 to print a string) always goes in AX; in Linux it always goes in EAX. As in the example,if we want to print out a string we use the "write" syscall, which is function number 4. We put '4' in EAX,the number of the file descriptor to write to in EBX (in this case '1', the screen), the location of thestring to print in ECX (mov ecx,hello), and the length of the string in EDX (mov ecx,helloLen).Then we call the kernel interrupt (int 80h), and voila!

总之,这个文档让我对linux汇编有了更清晰的理解,强烈推荐。

写完这个helloworld,还想用gdb调试哈,开始我只知道gcc -g选项可以是编译的可执行文件可调试,但是helloworld.o是用ld来链接,用gcc -g试了哈,但报错信息很明显,我把.asm文件里的入口写为main就好了,应该很好理解。

下面是gdb的一些使用吧,我就写出我用过的吧,具体就不怎么解释,看nasm相关文档吧,写下来就是让自己记下来吧:

breakpoint main

run

set disassembly-flavor intel

disassemble main

nexti


然后用测试了哈下一个在command line下写文件的asm代码,感觉linux下汇编代码的确比dos简单些,就是关于代码开头那三个pop没怎么看懂,想了一下明白了:

命令行的参数均存在该进程的栈中,然后pop出3次才是指向文件名的地址,而ebx中在8号系统调用就应该是这。

把自己以后写的比就有价值的asm测试代码存在github吧,希望自己能坚持:

https://github.com/ricky-hust/asmdemo

最后感觉linux下汇编是不是一般都写32为代码啊,能写成dos那样16位吗?

附:linux下系统调用表:

http://docs.cs.up.ac.za/programming/asm/derick_tut/syscalls.html

你可能感兴趣的:(在linux环境下编写汇编)