Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable from assembler to C

#include <stdio.h>

int main(){
        __asm__ (
                "result:    \n\t"
                ".long 0    \n\t" 
                "rdtsc      \n\t"
                "movl %eax, %ecx\n\t"
                "rdtsc      \n\t"
                "subl %ecx, %eax\n\t"
                "movl %eax, result\n\t"
        );

        extern int result;
        printf("%d\n", result);
}

I would like to pass some data from assembler to main via the result variable. Is this possible? My assembler code causes a Segmentation fault (core dumped). I am using Ubuntu 15.10 x86_64, gcc 5.2.1.

like image 468
robert Avatar asked Nov 10 '22 01:11

robert


1 Answers

A better approach could be:

int main (void)
{
    unsigned before, after;

    __asm__
    (
        "rdtsc\n\t"
        "movl %%eax, %0\n\t"
        "rdtsc\n\t"
        : "=rm" (before), "=a" (after)
        : /* no inputs */
        : "edx"
    );

    /* TODO: check for after < before in case you were unlucky
     * to hit a wraparound */
    printf("%u\n", after - before);
    return 0;
}
like image 68
Jester Avatar answered Nov 14 '22 22:11

Jester