mike
mike

Reputation: 25

ASM code in C program causes segmentation fault

I included some sample ASM code in a small program to do a test.

My program is:

#include <stdio.h>

static inline
unsigned char inb (int port) {
    unsigned char data;
    asm volatile("inb %w1,%0" : "=a" (data) : "d" (port));
    return data;
}

int main()
{
    printf("hello world %d\n", inb(22));
    return 0;
}

When I run the program, it crashes with a segmentation fault when executing the ASM code. Could someone tell me what's wrong with this small program? Thanks a lot.

Upvotes: 2

Views: 586

Answers (3)

Mohanraj
Mohanraj

Reputation: 4200

You syntax is absolutely correct. Just find and use the valid or unused port on your system.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182609

You need to use ioperm before you're allowed to use port I/O. Also, note the kernel already provides inb and outb functions.

Use ioperm(2) or alternatively iopl(2) to tell the kernel to allow the user space application to access the I/O ports in question. Failure to do this will cause the application to receive a segmentation fault.

Upvotes: 7

Alexey Frunze
Alexey Frunze

Reputation: 62048

If your OS is Windows or Linux, most likely your program is terminated because the OS doesn't allow regular applications access I/O ports.

Upvotes: 1

Related Questions