@zifehng
2017-04-24T02:21:46.000000Z
字数 2470
阅读 2161
linux EFAULT IS_ERR
kernel version: linux-4.9.13
在内核中定义了一些列错误码,以指示不同的出错情况:
include/uapi/asm-generic/errno-base.h
#ifndef _ASM_GENERIC_ERRNO_BASE_H#define _ASM_GENERIC_ERRNO_BASE_H#define EPERM 1 /* Operation not permitted */#define ENOENT 2 /* No such file or directory */#define ESRCH 3 /* No such process */#define EINTR 4 /* Interrupted system call */#define EIO 5 /* I/O error */#define ENXIO 6 /* No such device or address */#define E2BIG 7 /* Argument list too long */#define ENOEXEC 8 /* Exec format error */#define EBADF 9 /* Bad file number */#define ECHILD 10 /* No child processes */#define EAGAIN 11 /* Try again */#define ENOMEM 12 /* Out of memory */#define EACCES 13 /* Permission denied */#define EFAULT 14 /* Bad address */#define ENOTBLK 15 /* Block device required */#define EBUSY 16 /* Device or resource busy */#define EEXIST 17 /* File exists */#define EXDEV 18 /* Cross-device link */#define ENODEV 19 /* No such device */#define ENOTDIR 20 /* Not a directory */#define EISDIR 21 /* Is a directory */#define EINVAL 22 /* Invalid argument */#define ENFILE 23 /* File table overflow */#define EMFILE 24 /* Too many open files */#define ENOTTY 25 /* Not a typewriter */#define ETXTBSY 26 /* Text file busy */#define EFBIG 27 /* File too large */#define ENOSPC 28 /* No space left on device */#define ESPIPE 29 /* Illegal seek */#define EROFS 30 /* Read-only file system */#define EMLINK 31 /* Too many links */#define EPIPE 32 /* Broken pipe */#define EDOM 33 /* Math argument out of domain of func */#define ERANGE 34 /* Math result not representable */#endif
通常如果一个函数返回值是指针类型,在调用出错的情况下会返回NULL指针,但Linux内核对指针返回值作了更精妙的处理,使得出错情况能通过返回的指针体现出来。在内核中,有以下三种指针:
其中错误指针定义为指向内核空间保留区域(addr:0xffff000~0xffffffff, size: 4K)的指针,每一个地址都指示了一种出错情况。错误指针与错误码通过如下函数进行转换:
include/linux/err.h
......#define MAX_ERRNO 4095#define IS_ERR_VALUE(x) unlikely((unsigned long)(void *)(x) >= (unsigned long)-MAX_ERRNO)/* 将错误码转为错误指针 */static inline void * __must_check ERR_PTR(long error){return (void *) error;}/* 将错误指针转为错误码 */static inline long __must_check PTR_ERR(__force const void *ptr){return (long) ptr;}/* 判断指针是否为错误指针 */static inline bool __must_check IS_ERR(__force const void *ptr){return IS_ERR_VALUE((unsigned long)ptr);}static inline bool __must_check IS_ERR_OR_NULL(__force const void *ptr){return unlikely(!ptr) || IS_ERR_VALUE((unsigned long)ptr);}......
内联函数IS_ERR(),用来判断指针是否错误,将其一一展开:
IS_ERR(ptr)|IS_ERR_VALUE(ptr)|unlikely((unsigned long)(void *)(x) >= (unsigned long)-MAX_ERRNO)|unlikely((unsigned long)(void *)(x) >= (unsigned long)-4095)
表达式((unsigned long)-4095)的值就是0xfffff000,如果指针指向内核空间保留区域(0xfffff000~0xffffffff),IS_ERR()将返回flase,该指针被定义为错误指针。
内联函数PTR_ERR()与ERR_PTR(),提供错误指针与错误码相互转换的功能,涉及到类型强制转换,错误指针指向地址范围为0xfffff000~0xffffffff,因此转成错误码范围为-4096~-1。