当一个应用程序调用execve()执行系统调用时究竟发生了什么?
从应用程序空间来看
在深入Linux内核前,先来探索一下从用户空间开始的程序执行的过程。对于Linux而言,唯一的运行一个新程序运行的系统调用是execve(),其原型如下:
int execve(const char*filename, char *const argv[], char *const envp[]);
文件名参数指定了运行的程序,argv和envp是NULL结尾的列表,它们分别用于命令行参数和环境参数变量索引。一个简单的驱动框架do_execve.c用于探究其中的细节。Argv参数设置成zero、one、two,环境参数envp设置成ENVVAR1=1,ENVVAR=2,为了查看被执行程序的结果,使用show_info.c来打印命令行参数和环境参数。
一起打印这些参数验证了一个结果-命令行参数和环境参数被传递给了唤醒的程序。命二进制代码的令行参数argv[0]值是execve()函数调用者传递的。通常argv[0]是程序名字,但并不是一个标准。
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char*argv[])
{
char *args[] = {"zero","one", "two", NULL};
char *envp[] = {"ENVVAR1=1","ENVVAR2=2", NULL};
execve(argv[1], args, envp);
/* won't reach here if argv[1] can beexecuted */
fprintf(stderr, "Failed to execute'%s', %s\n", argv[1], strerror(errno));
return 1;
}
show_info.c
#include <stdio.h>
extern char **environ;
int main(int argc, char*argv[])
{
int ii;
char **p = environ;
for (ii = 0; ii < argc; ii++)
printf("argv[%d] = '%s'\n",ii, argv[ii]);
while (*p)
printf("%s\n", *p++);
return 0;
}
<pre name="code" class="javascript">show_info.sh
#!/bin/sh
echo "\$0 = '$0'"
ii=1
for arg in "$@";do
echo "\$$ii = '$arg'"
ii=`expr $ii + 1`
done
env
% ./do_execve ./show_info
argv[0] = 'zero'
argv[1] = 'one'
argv[2] = 'two'
ENVVAR1=1
ENVVAR2=2
当程序是由脚本启动而非二进制程序时情况变的略有不同,为了查看不同,使用show_info.sh脚本作为环境输出程序。执行的结果如下:
% ./do_execve ./show_info.sh
$0 = './show_info.sh'
$1 = 'one'
$2 = 'two'
ENVVAR1=1
ENVVAR2=2
PWD=/home/drysdale/src/lwn/exec
首先,环境参数获得了一个额外参数PWD,该参数指示的是当前的目录。其次,第一个命令行参数变成了脚本的名字而不是程序指定的“zero”。一个额外的环境参数表明/bin/sh脚本会解析PWD参数,但是内核自身修改了该参数。
% cat ./wrapper
#!./show_info
% ./do_execve ./wrapper
argv[0] = './show_info'
argv[1] = './wrapper'
argv[2] = 'one'
argv[3] = 'two'
ENVVAR1=1
ENVVAR2=2
更精确点,内核使用两个参数替代了“zero”参数-解析脚本程序的名字以及脚本程序源码文件的名字。如果脚本的第一行同样包括命令行参数,第三个参数同样会被插入:
% cat ./wrapper_args
#!./show_info -a -b -c
% ./do_execve ./wrapper_args
argv[0] = './show_info'
argv[1] = '-a -b -c'
argv[2] = './wrapper_args'
argv[3] = 'one'
argv[4] = 'two'
ENVVAR1=1
ENVVAR2=2
到这里,我们使用封装脚本可以继续这种一个参数产生两个参数的参数变换。
argv[0]: 'zero'=>'./wrapper4'=>'./wrapper3'=>'./wrapper2'=>'./wrapper' =>'./show_info'
argv[1]: 'one' './wrapper5' './wrapper4' './wrapper3' './wrapper2' './wrapper'
argv[2]: 'two' 'one' './wrapper5' './wrapper4' './wrapper3' './wrapper2'
argv[3]: 'two' 'one' './wrapper5' './wrapper4' './wrapper3'
argv[4]: 'two' 'one' './wrapper5' './wrapper4'
argv[5]: 'two' 'one' './wrapper5'
argv[6]: 'two' 'one'
argv[7]: 'two'
但是这种方法并不能一直迭代下去,一旦封装的层数太多,就会产生ELOOP错误。
% ./do_execve ./wrapper6
Failed to execute './wrapper6', Too many levels of symbolic links
内核态:struct linux_binprm
现在来一探execve()系统调用的实现代码。先前的一篇文章探究过一般系统调用的结构以及execve()的特殊处理。所以我们继续fs/exec.c文件的do_execve_common函数分析。该函数的主要功能是构建一个struct linux_binprm结构体实例,该结构体描述了当前唤醒程序的操作。该结构体:
注:该结构体摘自3.10+50版本内核
struct linux_binprm {
char buf[BINPRM_BUF_SIZE];
#ifdef CONFIG_MMU
struct vm_area_struct *vma;
unsigned long vma_pages;
#else
# define MAX_ARG_PAGES 32
struct page *page[MAX_ARG_PAGES];
#endif
struct mm_struct *mm;
unsigned long p; /* current top of mem */
unsigned int
cred_prepared:1,/* true if creds already prepared (multiple
* preps happen for interpreters) */
cap_effective:1;/* true if has elevated effective capabilities,
* false if not; except for init which inherits
* its parent's caps anyway */
#ifdef __alpha__
unsigned int taso:1;
#endif
unsigned int recursion_depth;
struct file * file;
struct cred *cred; /* new credentials */
int unsafe; /* how unsafe this exec is (mask of LSM_UNSAFE_*) */
unsigned int per_clear; /* bits to clear in current->personality */
int argc, envc;
const char * filename; /* Name of binary as seen by procps */
const char * interp; /* Name of the binary really executed. Most
of the time same as filename, but could be
different for binfmt_{misc,script} */
unsigned interp_flags;
unsigned interp_data;
unsigned long loader, exec;
char tcomm[TASK_COMM_LEN];
};
- 其*file成员指向为唤醒的程序刚打开的struct file类型的文件,这使得内核能够读取该文件的内核,并决定如何处理该文件。
- filename和interp被设置成包含该程序的文件名,filename在procps中显示,通常interp则是执行的二进制程序的名字,它们并不总是一样的。
- bprm_init()函数分配并设置struct mm_struct和struct vm_area_struct数据结构,这些数据结构用于处理新程序的虚拟内存。特别的,新程序的虚拟地址末尾设置该CPU架构的最高地址,其栈将向下增长。
- p为新程序标记内存的顶端边界,但是为栈在顶端边界预留NULL指针。当更多的信息添加进来时P的值将向下更新。
- argc和envc设置成参数个数和环境参数个数,这样该信息可以传递给由其唤醒的程序。
- unsafe被设置成该程序可能不安全的掩码,例如,如果程序是否正被ptrace跟踪或者PR_SET_NO_NEW_PRIVS 标志是否被设置。LinuxSecurity Module(LSM)也许会使用这一信息拒绝程序运行。
- cred是一个单独分配的struct cred类型的变量,该变量存储新程序的权能,它们继承与调用execve()函数的进程,但是可以使用setuid/setgid更新权能,由于setuid/setgid一些对安全性有害的特性,一些兼容性特性也被禁止了。per_clear记录了current->personality中要被清除的比特。
- security成员允许LSM使用linux_binprm存储LSM特定的信息;使用security_bprm_set_creds()函数和bprm_set_creds钩子通知LSM模块。
- buf空间存储来自程序文件前128字节内容,这些内容包括了二进制文件的类型。
这个建立过程中取决于特定文件的部分在prepare_binprm()函数内部执行;如果一个不同文件(如脚本解析程序)运行,这个函数可能还会被调用。
最后,被唤醒并得到执行的程序将信息存储在新程序的栈顶部,复制使用的函数是copy_strings()和copy_strings_kernel()。首先函数名被放入栈中(其在内存中的地址被存在了linux_bprm结构体的exec变量里了),然后是所有的环境变量,然后是参数,最后栈看起来像:
---------Memory limit---------
NULL pointer
program_filename string
envp[envc-1] string
...
envp[1] string
envp[0] string
argv[argc-1] string
...
argv[1] string
argv[0] string
二进制处理函数迭代struct linux_binfmt
得到了一个完整的linux_binprm,执行程序的真正工作在exec_binprm()和search_binary_handler()函数中完成。代码迭代structlinux_binfmt结构体,每一个这类的结构体对应一种二进制程序处理方法。一个二进制处理函数可能由内核模块定义,所以每一种格式的二进制程序名为try_module_get()的函数会被调用,以确保正被执行的程序不能被其它进程加载。
对每个structlinux_binfmt处理对象,load_binary()函数会被调用,该函数的参数是linux_binprm。如果处理函数支持二进制格式,其会文件能够运行做任何事并且返回success(>=0)。否则,处理函数返回错误码(<0)并继续迭代下一个处理函数。
一个程序可能依靠另一个程序才能运行,一个很明显的例子是可执行脚本,可执行脚本会唤醒脚本解析器。为了处理这类情况,search_binary_handler()代码能够被递归调用,重复使用linux_binprm对象。然而,递归的深度被限制以防止无限递归,返回如上的ELOOP错误码。
在操作时系统的LSM模块也有一个决定权,在二进制格式迭代开始前,bprm_check_security LSM钩子会被触发,以允许LSM决定是否允许迭代。为了完成这个功能,也许会使用先前存储在linux_binfmt的security成员。
迭代的最后,如果没有函数能够处理二进制文件(并且至少根据前四个字节,文件看起来时二进制而非文本文件),代码也会尝试加载一个叫“binfmt-XXX”的模块,XXX是程序文件的前三、四字节的十六进制值。这是很早的机制(96年在linux 1.3.57就加入内核了),该机制允许一个更加灵活的方法关联二进制格式文件和它们的处理函数。更加现代的方法是使用binfmt_misc机制(一个更加灵活的方法)实现类似的功能。
二进制格式:
内核支持的二进制文件格式。搜索structlinux_binfmt的注册(通过register_binfmt()和insert_binfmt())可以收集到这些格式,fs/Kconfig.binfmts文件有关于它们的配置和解释。
binfmt_script.c 支持解释性脚本,以#!开始。
Linux/fs/binfmt_script.c
1 /*
2 * linux/fs/binfmt_script.c
3 *
4 * Copyright (C) 1996 Martin von Löwis
5 * original #!-checking implemented by tytso.
6 */
7
8 #include <linux/module.h>
9 #include <linux/string.h>
10 #include <linux/stat.h>
11 #include <linux/binfmts.h>
12 #include <linux/init.h>
13 #include <linux/file.h>
14 #include <linux/err.h>
15 #include <linux/fs.h>
16
17 static int load_script(struct linux_binprm *bprm)
18 {
19 const char *i_arg, *i_name;
20 char *cp;
21 struct file *file;
22 char interp[BINPRM_BUF_SIZE];
23 int retval;
24
25 if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))
26 return -ENOEXEC;
27 /*
28 * This section does the #! interpretation.
29 * Sorta complicated, but hopefully it will work. -TYT
30 */
31
32 allow_write_access(bprm->file);
33 fput(bprm->file);
34 bprm->file = NULL;
35
36 bprm->buf[BINPRM_BUF_SIZE - 1] = '\0';
37 if ((cp = strchr(bprm->buf, '\n')) == NULL)
38 cp = bprm->buf+BINPRM_BUF_SIZE-1;
39 *cp = '\0';
40 while (cp > bprm->buf) {
41 cp--;
42 if ((*cp == ' ') || (*cp == '\t'))
43 *cp = '\0';
44 else
45 break;
46 }
47 for (cp = bprm->buf+2; (*cp == ' ') || (*cp == '\t'); cp++);
48 if (*cp == '\0')
49 return -ENOEXEC; /* No interpreter name found */
50 i_name = cp;
51 i_arg = NULL;
52 for ( ; *cp && (*cp != ' ') && (*cp != '\t'); cp++)
53 /* nothing */ ;
54 while ((*cp == ' ') || (*cp == '\t'))
55 *cp++ = '\0';
56 if (*cp)
57 i_arg = cp;
58 strcpy (interp, i_name);
59 /*
60 * OK, we've parsed out the interpreter name and
61 * (optional) argument.
62 * Splice in (1) the interpreter's name for argv[0]
63 * (2) (optional) argument to interpreter
64 * (3) filename of shell script (replace argv[0])
65 *
66 * This is done in reverse order, because of how the
67 * user environment and arguments are stored.
68 */
69 retval = remove_arg_zero(bprm);
70 if (retval)
71 return retval;
72 retval = copy_strings_kernel(1, &bprm->interp, bprm);
73 if (retval < 0) return retval;
74 bprm->argc++;
75 if (i_arg) {
76 retval = copy_strings_kernel(1, &i_arg, bprm);
77 if (retval < 0) return retval;
78 bprm->argc++;
79 }
80 retval = copy_strings_kernel(1, &i_name, bprm);
81 if (retval) return retval;
82 bprm->argc++;
83 retval = bprm_change_interp(interp, bprm);
84 if (retval < 0)
85 return retval;
86
87 /*
88 * OK, now restart the process with the interpreter's dentry.
89 */
90 file = open_exec(interp);
91 if (IS_ERR(file))
92 return PTR_ERR(file);
93
94 bprm->file = file;
95 retval = prepare_binprm(bprm);
96 if (retval < 0)
97 return retval;
98 return search_binary_handler(bprm);
99 }
100
101 static struct linux_binfmt script_format = {
102 .module = THIS_MODULE,
103 .load_binary = load_script,
104 };
105
106 static int __init init_script_binfmt(void)
107 {
108 register_binfmt(&script_format);
109 return 0;
110 }
111
112 static void __exit exit_script_binfmt(void)
113 {
114 unregister_binfmt(&script_format);
115 }
116
117 core_initcall(init_script_binfmt);
118 module_exit(exit_script_binfmt);
119 MODULE_LICENSE("GPL");
120
binfmt_misc.c:根据运行时配置,支持各种类型的二进制格式。
Linux/fs/binfmt_misc.c
1 /*
2 * binfmt_misc.c
3 *
4 * Copyright (C) 1997 Richard Günther
5 *
6 * binfmt_misc detects binaries via a magic or filename extension and invokes
7 * a specified wrapper. This should obsolete binfmt_java, binfmt_em86 and
8 * binfmt_mz.
9 *
10 * 1997-04-25 first version
11 * [...]
12 * 1997-05-19 cleanup
13 * 1997-06-26 hpa: pass the real filename rather than argv[0]
14 * 1997-06-30 minor cleanup
15 * 1997-08-09 removed extension stripping, locking cleanup
16 * 2001-02-28 AV: rewritten into something that resembles C. Original didn't.
17 */
18
19 #include <linux/module.h>
20 #include <linux/init.h>
21 #include <linux/sched.h>
22 #include <linux/magic.h>
23 #include <linux/binfmts.h>
24 #include <linux/slab.h>
25 #include <linux/ctype.h>
26 #include <linux/string_helpers.h>
27 #include <linux/file.h>
28 #include <linux/pagemap.h>
29 #include <linux/namei.h>
30 #include <linux/mount.h>
31 #include <linux/syscalls.h>
32 #include <linux/fs.h>
33
34 #include <asm/uaccess.h>
35
36 enum {
37 VERBOSE_STATUS = 1 /* make it zero to save 400 bytes kernel memory */
38 };
39
40 static LIST_HEAD(entries);
41 static int enabled = 1;
42
43 enum {Enabled, Magic};
44 #define MISC_FMT_PRESERVE_ARGV0 (1<<31)
45 #define MISC_FMT_OPEN_BINARY (1<<30)
46 #define MISC_FMT_CREDENTIALS (1<<29)
47
48 typedef struct {
49 struct list_head list;
50 unsigned long flags; /* type, status, etc. */
51 int offset; /* offset of magic */
52 int size; /* size of magic/mask */
53 char *magic; /* magic or filename extension */
54 char *mask; /* mask, NULL for exact match */
55 char *interpreter; /* filename of interpreter */
56 char *name;
57 struct dentry *dentry;
58 } Node;
59
60 static DEFINE_RWLOCK(entries_lock);
61 static struct file_system_type bm_fs_type;
62 static struct vfsmount *bm_mnt;
63 static int entry_count;
64
65 /*
66 * Max length of the register string. Determined by:
67 * - 7 delimiters
68 * - name: ~50 bytes
69 * - type: 1 byte
70 * - offset: 3 bytes (has to be smaller than BINPRM_BUF_SIZE)
71 * - magic: 128 bytes (512 in escaped form)
72 * - mask: 128 bytes (512 in escaped form)
73 * - interp: ~50 bytes
74 * - flags: 5 bytes
75 * Round that up a bit, and then back off to hold the internal data
76 * (like struct Node).
77 */
78 #define MAX_REGISTER_LENGTH 1920
79
80 /*
81 * Check if we support the binfmt
82 * if we do, return the node, else NULL
83 * locking is done in load_misc_binary
84 */
85 static Node *check_file(struct linux_binprm *bprm)
86 {
87 char *p = strrchr(bprm->interp, '.');
88 struct list_head *l;
89
90 list_for_each(l, &entries) {
91 Node *e = list_entry(l, Node, list);
92 char *s;
93 int j;
94
95 if (!test_bit(Enabled, &e->flags))
96 continue;
97
98 if (!test_bit(Magic, &e->flags)) {
99 if (p && !strcmp(e->magic, p + 1))
100 return e;
101 continue;
102 }
103
104 s = bprm->buf + e->offset;
105 if (e->mask) {
106 for (j = 0; j < e->size; j++)
107 if ((*s++ ^ e->magic[j]) & e->mask[j])
108 break;
109 } else {
110 for (j = 0; j < e->size; j++)
111 if ((*s++ ^ e->magic[j]))
112 break;
113 }
114 if (j == e->size)
115 return e;
116 }
117 return NULL;
118 }
119
120 /*
121 * the loader itself
122 */
123 static int load_misc_binary(struct linux_binprm *bprm)
124 {
125 Node *fmt;
126 struct file * interp_file = NULL;
127 char iname[BINPRM_BUF_SIZE];
128 const char *iname_addr = iname;
129 int retval;
130 int fd_binary = -1;
131
132 retval = -ENOEXEC;
133 if (!enabled)
134 goto _ret;
135
136 /* to keep locking time low, we copy the interpreter string */
137 read_lock(&entries_lock);
138 fmt = check_file(bprm);
139 if (fmt)
140 strlcpy(iname, fmt->interpreter, BINPRM_BUF_SIZE);
141 read_unlock(&entries_lock);
142 if (!fmt)
143 goto _ret;
144
145 if (!(fmt->flags & MISC_FMT_PRESERVE_ARGV0)) {
146 retval = remove_arg_zero(bprm);
147 if (retval)
148 goto _ret;
149 }
150
151 if (fmt->flags & MISC_FMT_OPEN_BINARY) {
152
153 /* if the binary should be opened on behalf of the
154 * interpreter than keep it open and assign descriptor
155 * to it */
156 fd_binary = get_unused_fd();
157 if (fd_binary < 0) {
158 retval = fd_binary;
159 goto _ret;
160 }
161 fd_install(fd_binary, bprm->file);
162
163 /* if the binary is not readable than enforce mm->dumpable=0
164 regardless of the interpreter's permissions */
165 would_dump(bprm, bprm->file);
166
167 allow_write_access(bprm->file);
168 bprm->file = NULL;
169
170 /* mark the bprm that fd should be passed to interp */
171 bprm->interp_flags |= BINPRM_FLAGS_EXECFD;
172 bprm->interp_data = fd_binary;
173
174 } else {
175 allow_write_access(bprm->file);
176 fput(bprm->file);
177 bprm->file = NULL;
178 }
179 /* make argv[1] be the path to the binary */
180 retval = copy_strings_kernel (1, &bprm->interp, bprm);
181 if (retval < 0)
182 goto _error;
183 bprm->argc++;
184
185 /* add the interp as argv[0] */
186 retval = copy_strings_kernel (1, &iname_addr, bprm);
187 if (retval < 0)
188 goto _error;
189 bprm->argc ++;
190
191 /* Update interp in case binfmt_script needs it. */
192 retval = bprm_change_interp(iname, bprm);
193 if (retval < 0)
194 goto _error;
195
196 interp_file = open_exec (iname);
197 retval = PTR_ERR (interp_file);
198 if (IS_ERR (interp_file))
199 goto _error;
200
201 bprm->file = interp_file;
202 if (fmt->flags & MISC_FMT_CREDENTIALS) {
203 /*
204 * No need to call prepare_binprm(), it's already been
205 * done. bprm->buf is stale, update from interp_file.
206 */
207 memset(bprm->buf, 0, BINPRM_BUF_SIZE);
208 retval = kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
209 } else
210 retval = prepare_binprm (bprm);
211
212 if (retval < 0)
213 goto _error;
214
215 retval = search_binary_handler(bprm);
216 if (retval < 0)
217 goto _error;
218
219 _ret:
220 return retval;
221 _error:
222 if (fd_binary > 0)
223 sys_close(fd_binary);
224 bprm->interp_flags = 0;
225 bprm->interp_data = 0;
226 goto _ret;
227 }
228
229 /* Command parsers */
230
231 /*
232 * parses and copies one argument enclosed in del from *sp to *dp,
233 * recognising the \x special.
234 * returns pointer to the copied argument or NULL in case of an
235 * error (and sets err) or null argument length.
236 */
237 static char *scanarg(char *s, char del)
238 {
239 char c;
240
241 while ((c = *s++) != del) {
242 if (c == '\\' && *s == 'x') {
243 s++;
244 if (!isxdigit(*s++))
245 return NULL;
246 if (!isxdigit(*s++))
247 return NULL;
248 }
249 }
250 return s;
251 }
252
253 static char * check_special_flags (char * sfs, Node * e)
254 {
255 char * p = sfs;
256 int cont = 1;
257
258 /* special flags */
259 while (cont) {
260 switch (*p) {
261 case 'P':
262 p++;
263 e->flags |= MISC_FMT_PRESERVE_ARGV0;
264 break;
265 case 'O':
266 p++;
267 e->flags |= MISC_FMT_OPEN_BINARY;
268 break;
269 case 'C':
270 p++;
271 /* this flags also implies the
272 open-binary flag */
273 e->flags |= (MISC_FMT_CREDENTIALS |
274 MISC_FMT_OPEN_BINARY);
275 break;
276 default:
277 cont = 0;
278 }
279 }
280
281 return p;
282 }
283 /*
284 * This registers a new binary format, it recognises the syntax
285 * ':name:type:offset:magic:mask:interpreter:flags'
286 * where the ':' is the IFS, that can be chosen with the first char
287 */
288 static Node *create_entry(const char __user *buffer, size_t count)
289 {
290 Node *e;
291 int memsize, err;
292 char *buf, *p;
293 char del;
294
295 /* some sanity checks */
296 err = -EINVAL;
297 if ((count < 11) || (count > MAX_REGISTER_LENGTH))
298 goto out;
299
300 err = -ENOMEM;
301 memsize = sizeof(Node) + count + 8;
302 e = kmalloc(memsize, GFP_USER);
303 if (!e)
304 goto out;
305
306 p = buf = (char *)e + sizeof(Node);
307
308 memset(e, 0, sizeof(Node));
309 if (copy_from_user(buf, buffer, count))
310 goto Efault;
311
312 del = *p++; /* delimeter */
313
314 memset(buf+count, del, 8);
315
316 e->name = p;
317 p = strchr(p, del);
318 if (!p)
319 goto Einval;
320 *p++ = '\0';
321 if (!e->name[0] ||
322 !strcmp(e->name, ".") ||
323 !strcmp(e->name, "..") ||
324 strchr(e->name, '/'))
325 goto Einval;
326 switch (*p++) {
327 case 'E': e->flags = 1<<Enabled; break;
328 case 'M': e->flags = (1<<Enabled) | (1<<Magic); break;
329 default: goto Einval;
330 }
331 if (*p++ != del)
332 goto Einval;
333 if (test_bit(Magic, &e->flags)) {
334 char *s = strchr(p, del);
335 if (!s)
336 goto Einval;
337 *s++ = '\0';
338 e->offset = simple_strtoul(p, &p, 10);
339 if (*p++)
340 goto Einval;
341 e->magic = p;
342 p = scanarg(p, del);
343 if (!p)
344 goto Einval;
345 p[-1] = '\0';
346 if (!e->magic[0])
347 goto Einval;
348 e->mask = p;
349 p = scanarg(p, del);
350 if (!p)
351 goto Einval;
352 p[-1] = '\0';
353 if (!e->mask[0])
354 e->mask = NULL;
355 e->size = string_unescape_inplace(e->magic, UNESCAPE_HEX);
356 if (e->mask &&
357 string_unescape_inplace(e->mask, UNESCAPE_HEX) != e->size)
358 goto Einval;
359 if (e->size + e->offset > BINPRM_BUF_SIZE)
360 goto Einval;
361 } else {
362 p = strchr(p, del);
363 if (!p)
364 goto Einval;
365 *p++ = '\0';
366 e->magic = p;
367 p = strchr(p, del);
368 if (!p)
369 goto Einval;
370 *p++ = '\0';
371 if (!e->magic[0] || strchr(e->magic, '/'))
372 goto Einval;
373 p = strchr(p, del);
374 if (!p)
375 goto Einval;
376 *p++ = '\0';
377 }
378 e->interpreter = p;
379 p = strchr(p, del);
380 if (!p)
381 goto Einval;
382 *p++ = '\0';
383 if (!e->interpreter[0])
384 goto Einval;
385
386
387 p = check_special_flags (p, e);
388
389 if (*p == '\n')
390 p++;
391 if (p != buf + count)
392 goto Einval;
393 return e;
394
395 out:
396 return ERR_PTR(err);
397
398 Efault:
399 kfree(e);
400 return ERR_PTR(-EFAULT);
401 Einval:
402 kfree(e);
403 return ERR_PTR(-EINVAL);
404 }
405
406 /*
407 * Set status of entry/binfmt_misc:
408 * '1' enables, '' disables and '-1' clears entry/binfmt_misc
409 */
410 static int parse_command(const char __user *buffer, size_t count)
411 {
412 char s[4];
413
414 if (count > 3)
415 return -EINVAL;
416 if (copy_from_user(s, buffer, count))
417 return -EFAULT;
418 if (!count)
419 return 0;
420 if (s[count-1] == '\n')
421 count--;
422 if (count == 1 && s[0] == '')
423 return 1;
424 if (count == 1 && s[0] == '1')
425 return 2;
426 if (count == 2 && s[0] == '-' && s[1] == '1')
427 return 3;
428 return -EINVAL;
429 }
430
431 /* generic stuff */
432
433 static void entry_status(Node *e, char *page)
434 {
435 char *dp;
436 char *status = "disabled";
437 const char * flags = "flags: ";
438
439 if (test_bit(Enabled, &e->flags))
440 status = "enabled";
441
442 if (!VERBOSE_STATUS) {
443 sprintf(page, "%s\n", status);
444 return;
445 }
446
447 sprintf(page, "%s\ninterpreter %s\n", status, e->interpreter);
448 dp = page + strlen(page);
449
450 /* print the special flags */
451 sprintf (dp, "%s", flags);
452 dp += strlen (flags);
453 if (e->flags & MISC_FMT_PRESERVE_ARGV0) {
454 *dp ++ = 'P';
455 }
456 if (e->flags & MISC_FMT_OPEN_BINARY) {
457 *dp ++ = 'O';
458 }
459 if (e->flags & MISC_FMT_CREDENTIALS) {
460 *dp ++ = 'C';
461 }
462 *dp ++ = '\n';
463
464
465 if (!test_bit(Magic, &e->flags)) {
466 sprintf(dp, "extension .%s\n", e->magic);
467 } else {
468 int i;
469
470 sprintf(dp, "offset %i\nmagic ", e->offset);
471 dp = page + strlen(page);
472 for (i = 0; i < e->size; i++) {
473 sprintf(dp, "%02x", 0xff & (int) (e->magic[i]));
474 dp += 2;
475 }
476 if (e->mask) {
477 sprintf(dp, "\nmask ");
478 dp += 6;
479 for (i = 0; i < e->size; i++) {
480 sprintf(dp, "%02x", 0xff & (int) (e->mask[i]));
481 dp += 2;
482 }
483 }
484 *dp++ = '\n';
485 *dp = '\0';
486 }
487 }
488
489 static struct inode *bm_get_inode(struct super_block *sb, int mode)
490 {
491 struct inode * inode = new_inode(sb);
492
493 if (inode) {
494 inode->i_ino = get_next_ino();
495 inode->i_mode = mode;
496 inode->i_atime = inode->i_mtime = inode->i_ctime =
497 current_fs_time(inode->i_sb);
498 }
499 return inode;
500 }
501
502 static void bm_evict_inode(struct inode *inode)
503 {
504 clear_inode(inode);
505 kfree(inode->i_private);
506 }
507
508 static void kill_node(Node *e)
509 {
510 struct dentry *dentry;
511
512 write_lock(&entries_lock);
513 dentry = e->dentry;
514 if (dentry) {
515 list_del_init(&e->list);
516 e->dentry = NULL;
517 }
518 write_unlock(&entries_lock);
519
520 if (dentry) {
521 drop_nlink(dentry->d_inode);
522 d_drop(dentry);
523 dput(dentry);
524 simple_release_fs(&bm_mnt, &entry_count);
525 }
526 }
527
528 /* /<entry> */
529
530 static ssize_t
531 bm_entry_read(struct file * file, char __user * buf, size_t nbytes, loff_t *ppos)
532 {
533 Node *e = file_inode(file)->i_private;
534 ssize_t res;
535 char *page;
536
537 if (!(page = (char*) __get_free_page(GFP_KERNEL)))
538 return -ENOMEM;
539
540 entry_status(e, page);
541
542 res = simple_read_from_buffer(buf, nbytes, ppos, page, strlen(page));
543
544 free_page((unsigned long) page);
545 return res;
546 }
547
548 static ssize_t bm_entry_write(struct file *file, const char __user *buffer,
549 size_t count, loff_t *ppos)
550 {
551 struct dentry *root;
552 Node *e = file_inode(file)->i_private;
553 int res = parse_command(buffer, count);
554
555 switch (res) {
556 case 1: clear_bit(Enabled, &e->flags);
557 break;
558 case 2: set_bit(Enabled, &e->flags);
559 break;
560 case 3: root = dget(file->f_path.dentry->d_sb->s_root);
561 mutex_lock(&root->d_inode->i_mutex);
562
563 kill_node(e);
564
565 mutex_unlock(&root->d_inode->i_mutex);
566 dput(root);
567 break;
568 default: return res;
569 }
570 return count;
571 }
572
573 static const struct file_operations bm_entry_operations = {
574 .read = bm_entry_read,
575 .write = bm_entry_write,
576 .llseek = default_llseek,
577 };
578
579 /* /register */
580
581 static ssize_t bm_register_write(struct file *file, const char __user *buffer,
582 size_t count, loff_t *ppos)
583 {
584 Node *e;
585 struct inode *inode;
586 struct dentry *root, *dentry;
587 struct super_block *sb = file->f_path.dentry->d_sb;
588 int err = 0;
589
590 e = create_entry(buffer, count);
591
592 if (IS_ERR(e))
593 return PTR_ERR(e);
594
595 root = dget(sb->s_root);
596 mutex_lock(&root->d_inode->i_mutex);
597 dentry = lookup_one_len(e->name, root, strlen(e->name));
598 err = PTR_ERR(dentry);
599 if (IS_ERR(dentry))
600 goto out;
601
602 err = -EEXIST;
603 if (dentry->d_inode)
604 goto out2;
605
606 inode = bm_get_inode(sb, S_IFREG | 0644);
607
608 err = -ENOMEM;
609 if (!inode)
610 goto out2;
611
612 err = simple_pin_fs(&bm_fs_type, &bm_mnt, &entry_count);
613 if (err) {
614 iput(inode);
615 inode = NULL;
616 goto out2;
617 }
618
619 e->dentry = dget(dentry);
620 inode->i_private = e;
621 inode->i_fop = &bm_entry_operations;
622
623 d_instantiate(dentry, inode);
624 write_lock(&entries_lock);
625 list_add(&e->list, &entries);
626 write_unlock(&entries_lock);
627
628 err = 0;
629 out2:
630 dput(dentry);
631 out:
632 mutex_unlock(&root->d_inode->i_mutex);
633 dput(root);
634
635 if (err) {
636 kfree(e);
637 return -EINVAL;
638 }
639 return count;
640 }
641
642 static const struct file_operations bm_register_operations = {
643 .write = bm_register_write,
644 .llseek = noop_llseek,
645 };
646
647 /* /status */
648
649 static ssize_t
650 bm_status_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
651 {
652 char *s = enabled ? "enabled\n" : "disabled\n";
653
654 return simple_read_from_buffer(buf, nbytes, ppos, s, strlen(s));
655 }
656
657 static ssize_t bm_status_write(struct file * file, const char __user * buffer,
658 size_t count, loff_t *ppos)
659 {
660 int res = parse_command(buffer, count);
661 struct dentry *root;
662
663 switch (res) {
664 case 1: enabled = 0; break;
665 case 2: enabled = 1; break;
666 case 3: root = dget(file->f_path.dentry->d_sb->s_root);
667 mutex_lock(&root->d_inode->i_mutex);
668
669 while (!list_empty(&entries))
670 kill_node(list_entry(entries.next, Node, list));
671
672 mutex_unlock(&root->d_inode->i_mutex);
673 dput(root);
674 break;
675 default: return res;
676 }
677 return count;
678 }
679
680 static const struct file_operations bm_status_operations = {
681 .read = bm_status_read,
682 .write = bm_status_write,
683 .llseek = default_llseek,
684 };
685
686 /* Superblock handling */
687
688 static const struct super_operations s_ops = {
689 .statfs = simple_statfs,
690 .evict_inode = bm_evict_inode,
691 };
692
693 static int bm_fill_super(struct super_block * sb, void * data, int silent)
694 {
695 static struct tree_descr bm_files[] = {
696 [2] = {"status", &bm_status_operations, S_IWUSR|S_IRUGO},
697 [3] = {"register", &bm_register_operations, S_IWUSR},
698 /* last one */ {""}
699 };
700 int err = simple_fill_super(sb, BINFMTFS_MAGIC, bm_files);
701 if (!err)
702 sb->s_op = &s_ops;
703 return err;
704 }
705
706 static struct dentry *bm_mount(struct file_system_type *fs_type,
707 int flags, const char *dev_name, void *data)
708 {
709 return mount_single(fs_type, flags, data, bm_fill_super);
710 }
711
712 static struct linux_binfmt misc_format = {
713 .module = THIS_MODULE,
714 .load_binary = load_misc_binary,
715 };
716
717 static struct file_system_type bm_fs_type = {
718 .owner = THIS_MODULE,
719 .name = "binfmt_misc",
720 .mount = bm_mount,
721 .kill_sb = kill_litter_super,
722 };
723 MODULE_ALIAS_FS("binfmt_misc");
724
725 static int __init init_misc_binfmt(void)
726 {
727 int err = register_filesystem(&bm_fs_type);
728 if (!err)
729 insert_binfmt(&misc_format);
730 return err;
731 }
732
733 static void __exit exit_misc_binfmt(void)
734 {
735 unregister_binfmt(&misc_format);
736 unregister_filesystem(&bm_fs_type);
737 }
738
739 core_initcall(init_misc_binfmt);
740 module_exit(exit_misc_binfmt);
741 MODULE_LICENSE("GPL");
742
binfmt_elf.c:ELF 格式文件支持
binfmt_aout.c:传统的a.out格式支持
binfmt_flat.c:支持平坦格式
binfmt_em86.c:支持在Alpha上运行intel ELF格式
binfmt_elf_fdpic.c:ELFFDPIC格式支持
binfmt_som.c:SOM格式支持 (HP/UXPA-RISC格式)
这些文件见fs目录,不再列出。
还有一些其它体系结构特定的格式。
脚本唤醒:binfmt_script.c
以#!开始被认为是脚本,由fs/binfmt_script.c处理。在检查前两个字节后,代码会继续解析脚本唤醒行的其它参数,将这些参数按空格分离。
有了这些信息,代码然后从栈的最顶端移除argv[0],然后将下面参数放入栈,调整linux_binprm的argc参数:
- 程序名
- 收集到的参数(可选)
- 解析器名
综合这些,可以得到文章开始处用户空间的输出内容,新程序的栈看起来如下:
---------Memory limit---------
NULL pointer
program_filename string
envp[envc-1] string
...
envp[1] string
envp[0] string
argv[argc-1] string
...
argv[1] string
program_filename string
( interpreter_args )
interpreter_filename string
代码同样改变了linux_binprm成员interp的值,该值是解析器文件的名字地址而不是脚本文件名。这解释了为什么linux_binprm结构体引用了两种字符串:一个(interp)是正在运行的程序,一个(filename)是由execve()唤醒的程序。类似的,linux_binprm的file成员也被更新为指向新的解析程序,前128字节被都取到buf开始的空间中。
Binfmt_misc.c
Miscellaneous 二进制格式通过运行时配置支持更灵活方法处理新的格式,配置内容能够包括:
- 如何识别支持的格式,基于文件名扩展或者一个特定偏移的魔数。
- 调用的解析程序,参数argv[1]将被传递给该程序。
一个例子是Java文件:检测到.class文件或者.jar文件就会调用JVM执行它们。这通常需要一个封装脚本提供命令行参数,这是由于这种格式二进制不提供参数功能。
这种格式的实现方式和上面描述的脚本的解析很类似,只是这里多一个匹配配置项的搜索,配置用于实现一些可选的细节(如移除argv[0])。
http://lwn.net/Articles/630262/