Xcode 环境下的汇编与 C/C++/ObjC

来源:互联网 发布:windows 10 rs4新功能 编辑:程序博客网 时间:2024/06/05 03:33
Xcode 环境下的汇编与 C/C++/ObjC (上)

本文汇编代码如未指明平台,默认是 Mac OS X(x86)。

预备知识:

1.汇编语言——稍高于机器语言的低级语言,书写风格在业界有 Intel、AT&T 两种风格。(此处的 Intel 不是指 Intel 的 CPU~~)Intel 风格就是天朝各大大学微机原理教科书里采用的那种风格,在 DOS & Windows 常用。AT&T 是 UNIX 家族(BSD + Linux) 系统的默认风格。

2. 至关重要的,Mac OS X 是基于 BSD 的, 不是 Linux 的。后面会说在汇编时的区别。

3.Xcode——苹果的集成开发环境。相信各位看官都用了,知道可以用来编译C、C++、Objective C程序。其实, Xcode 还能支持汇编开发,而且 还可以设置断点 调试 AT&T 风格的汇编代码。

正文:

(一)平台汇编语言代码比较

汇编语言的函数调用,参数传递和 Linux 是不一样的。

示例: Linux 平台的 print_info 函数 (Intel)

_print_info_s:# entry point for linker

movl    edx, len# message length

movl    ecx, msg# message to write

movl    ebx,0x1# file descriptor value

movleax, 0x4# system call number (sys_write)

int0x80 # call the kernel

ret

示例: Linux 平台的 print_info 函数 (AT&T)

_print_info_s:# entry point for linker

movl    $len, %edx # message length

movl    $msg, %ecx# message to write

movl    $0x1, %ebx# file descriptor value

movl$0x4, %eax# system call number (sys_write)

int$0x80 # call the kernel

ret

示例: Mac OS X 平台的 print_info 函数 (Intel)

_syscall:# declaring a kernel call function

int     0x80# make the system call

ret# return to the caller 

_print_info_s:# entry point for linker

push    len# message length

push    msg# message to write

push   0x1# file descriptor value

moveax, 0x4# system call number (sys_write)

call_syscall # call the kernel

addesp, 12 # clean the stack

ret

示例: Mac OS X 平台的 print_info 函数 (AT&T)

_syscall:# declaring a kernel call function

int      $0x80# make the system call

ret# return to the caller 

_print_info_s:# entry point for linker

pushl    $len# message length

pushl    $msg# message to write

pushl    $0x1# file descriptor value

movl$0x4, %eax# system call number (sys_write)

call_syscall # call the kernel

addl$12, %esp# clean the stack

ret   

Linux 参数传递主要是靠寄存器,而 BSD 主要靠堆栈。

(二)Xcode 开发

在Xcode里如果需要使用 Intel 风格的代码,请将扩展名改成 .nasm,如果是 AT&T ,那么.s 即可。

要在 C 代码里调用汇编写的函数,请在汇编里用 global (.globl) 导出符号

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明http://51test2003.blogbus.com/logs/32844080.html

原创粉丝点击