JAN*_*JAN 1 c assembly volatile system-calls
我正在尝试使用asm volatile编写read()系统调用的包装函数,但它不起作用,因为res不会更改其值.
这是代码:
ssize_t my_read(int fd, void *buf, size_t count)
{
ssize_t res;
__asm__ volatile(
"int $0x80" /* make the request to the OS */
: "=a" (res), /* return result in eax ("a") */
"+b" (fd), /* pass arg1 in ebx ("b") */
"+c" (buf), /* pass arg2 in ecx ("c") */
"+d" (count) /* pass arg3 in edx ("d") */
: "a" (5) /* passing the system call for read to %eax , with call number 5 */
: "memory", "cc"); /* announce to the compiler that the memory and condition codes have been modified */
/* The operating system will return a negative value on error;
* wrappers return -1 on error and set the errno global variable */
if (-125 <= res && res < 0)
{
errno = -res;
res = -1;
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
这是int main ():
int main() {
int fd = 432423;
char buf[128];
size_t count = 128;
my_read(fd, buf, count);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
难道我做错了什么 ?也许是因为volatile?
我试图调试代码,当Eclipse进入my_read(fd, buf, count); 并进入线路 __asm__ volatile(时my_read,它会失败并进入if (-125 <= res && res < 0)......
编辑:
ssize_t my_read(int fd, void *buf, size_t count)
{
ssize_t res;
__asm__ volatile(
"int $0x80" /* make the request to the OS */
: "=a" (res) /* return result in eax ("a") */
: "a" (5) , /* passing the system call for read to %eax , with call number 5 */
"b" (fd), /* pass arg1 in ebx ("b") */
"c" (buf), /* pass arg2 in ecx ("c") */
"d" (count) /* pass arg3 in edx ("d") */
: "memory", "cc"); /* announce to the compiler that the memory and condition codes have been modified */
/* The operating system will return a negative value on error;
* wrappers return -1 on error and set the errno global variable */
if (-125 <= res && res < 0)
{
errno = -res;
res = -1;
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
主要:
int main() {
int fd = 0;
char buf[128];
size_t count = 128;
my_read(fd, buf, count);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它失败并进入
if (-125 <= res && res < 0)
你在哪里期待它?
我希望读取系统调用失败-EINVAL,因为您没有在其中使用有效的文件描述符.
更新:
你从哪里得到的想法SYS_read是5?
在我的系统,SYS_read是3在32位模式,以及0在64位模式:
echo "#include <syscall.h>" | gcc -xc - -dD -E | grep ' __NR_read '
#define __NR_read 0
echo "#include <syscall.h>" | gcc -xc - -dD -E -m32 | grep ' __NR_read '
#define __NR_read 3
Run Code Online (Sandbox Code Playgroud)
假设你在32位系统上,你正在调用SYS_open,它失败了-EFAULT(-14),因为开放系统调用的第一个参数应该是文件名,而0(NULL)不是有效的文件名.