在C语言中调用汇编写的接口

-- TOC --

基本原理时,gcc将.c和.s文件分别编译成.o,ld链接所有.o。

Case One

$ cat casm.s
.globl hello_friend
.type hello_friend, @function

.section .data
message:
    .ascii "Hello, Friend!\n"
length:
    .int . - message

.section .text
hello_friend:
    mov $4, %eax
    mov $1, %ebx
    mov $message, %ecx
    mov length, %edx
    int $0x80
    ret
$ cat casm.c
extern void hello_friend();

void main()
{
  hello_friend();
}
$ 
$ gcc -m32 casm.s casm.c -o casm
$ ./casm
Hello, Friend!

Case Two

下面这个32位示例程序,字符串通过C语言传递给汇编定义的函数:

$ cat casm.s
.globl hello_friend
.type hello_friend, @function

.section .text
hello_friend:
    mov $4, %eax
    mov $1, %ebx
    mov 4(%esp), %ecx
    mov $0x0D, %edx  # 0x0D is fixed here!
    int $0x80
    ret
$ cat casm.c
extern void hello_friend(char *str);

void main()
{
  hello_friend("abcdefg12345\n");
}
$ gcc -m32 casm.s casm.c -o casm
$ ./casm
abcdefg12345

Case Three

Mixing C and Assembly Language

用一段汇编代码,实现从3个int64,找出最大的那个。

# -----------------------------------------------------------------------------
# A 64-bit function that returns the maximum value of its three 64-bit integer
# arguments.  The function has signature:
#
#   int64_t maxofthree(int64_t x, int64_t y, int64_t z)
#
# Note that the parameters have already been passed in rdi, rsi, and rdx.  We
# just have to return the value in rax.
# -----------------------------------------------------------------------------

        .globl  maxofthree

        .text
maxofthree:
        mov     %rdi, %rax              # result (rax) initially holds x
        cmp     %rsi, %rax              # is x less than y?
        cmovl   %rsi, %rax              # if so, set result to y
        cmp     %rdx, %rax              # is max(x,y) less than z?
        cmovl   %rdx, %rax              # if so, set result to z
        ret                             # the max will be in rax

下面是C代码,调用maxofthree这个global符号:

/*
 * callmaxofthree.c
 *
 * A small program that illustrates how to call the maxofthree function we wrote in
 * assembly language.
 */
#include <stdio.h>
#include <inttypes.h>

int64_t maxofthree(int64_t, int64_t, int64_t);

int main() {
    printf("%ld\n", maxofthree(1, -4, -7));
    printf("%ld\n", maxofthree(2, -6, 1));
    printf("%ld\n", maxofthree(2, 3, 1));
    printf("%ld\n", maxofthree(-2, 4, 3));
    printf("%ld\n", maxofthree(2, -6, 5));
    printf("%ld\n", maxofthree(2, 4, 6));
    return 0;
}

编译和输出:

$ gcc callmaxofthree.c maxofthree.s -o tt
$ ./tt
1
2
3
4
5
6

本文链接:https://cs.pynote.net/hd/asm/202302151/

-- EOF --

-- MORE --