1 /*
2 * linux/fs/exec.c
3 *
4 * Copyright (C) 1991, 1992 Linus Torvalds
5 */
6
7 /*
8 * #!-checking implemented by tytso.
9 */
10 /*
11 * Demand-loading implemented 01.12.91 - no need to read anything but
12 * the header into memory. The inode of the executable is put into
13 * "current->executable", and page faults do the actual loading. Clean.
14 *
15 * Once more I can proudly say that linux stood up to being changed: it
16 * was less than 2 hours work to get demand-loading completely implemented.
17 *
18 * Demand loading changed July 1993 by Eric Youngdale. Use mmap instead,
19 * current->executable is only used by the procfs. This allows a dispatch
20 * table to check for several different types of binary formats. We keep
21 * trying until we recognize the file or we run out of supported binary
22 * formats.
23 */
24
25 #include <linux/slab.h>
26 #include <linux/file.h>
27 #include <linux/fdtable.h>
28 #include <linux/mm.h>
29 #include <linux/stat.h>
30 #include <linux/fcntl.h>
31 #include <linux/smp_lock.h>
32 #include <linux/swap.h>
33 #include <linux/string.h>
34 #include <linux/init.h>
35 #include <linux/pagemap.h>
36 #include <linux/highmem.h>
37 #include <linux/spinlock.h>
38 #include <linux/key.h>
39 #include <linux/personality.h>
40 #include <linux/binfmts.h>
41 #include <linux/utsname.h>
42 #include <linux/pid_namespace.h>
43 #include <linux/module.h>
44 #include <linux/namei.h>
45 #include <linux/proc_fs.h>
46 #include <linux/mount.h>
47 #include <linux/security.h>
48 #include <linux/syscalls.h>
49 #include <linux/tsacct_kern.h>
50 #include <linux/cn_proc.h>
51 #include <linux/audit.h>
52 #include <linux/tracehook.h>
53 #include <linux/kmod.h>
54 #include <linux/fsnotify.h>
55
56 #include <asm/uaccess.h>
57 #include <asm/mmu_context.h>
58 #include <asm/tlb.h>
59 #include "internal.h"
60 #ifdef CONFIG_QEMU_TRACE
61 void qemu_trace_thread_name(char *name);
62 #endif
63
64 int core_uses_pid;
65 char core_pattern[CORENAME_MAX_SIZE] = "core";
66 int suid_dumpable = 0;
67
68 /* The maximal length of core_pattern is also specified in sysctl.c */
69
70 static LIST_HEAD(formats);
71 static DEFINE_RWLOCK(binfmt_lock);
72
register_binfmt(struct linux_binfmt * fmt)73 int register_binfmt(struct linux_binfmt * fmt)
74 {
75 if (!fmt)
76 return -EINVAL;
77 write_lock(&binfmt_lock);
78 list_add(&fmt->lh, &formats);
79 write_unlock(&binfmt_lock);
80 return 0;
81 }
82
83 EXPORT_SYMBOL(register_binfmt);
84
unregister_binfmt(struct linux_binfmt * fmt)85 void unregister_binfmt(struct linux_binfmt * fmt)
86 {
87 write_lock(&binfmt_lock);
88 list_del(&fmt->lh);
89 write_unlock(&binfmt_lock);
90 }
91
92 EXPORT_SYMBOL(unregister_binfmt);
93
put_binfmt(struct linux_binfmt * fmt)94 static inline void put_binfmt(struct linux_binfmt * fmt)
95 {
96 module_put(fmt->module);
97 }
98
99 /*
100 * Note that a shared library must be both readable and executable due to
101 * security reasons.
102 *
103 * Also note that we take the address to load from from the file itself.
104 */
SYSCALL_DEFINE1(uselib,const char __user *,library)105 SYSCALL_DEFINE1(uselib, const char __user *, library)
106 {
107 struct file *file;
108 struct nameidata nd;
109 char *tmp = getname(library);
110 int error = PTR_ERR(tmp);
111
112 if (!IS_ERR(tmp)) {
113 error = path_lookup_open(AT_FDCWD, tmp,
114 LOOKUP_FOLLOW, &nd,
115 FMODE_READ|FMODE_EXEC);
116 putname(tmp);
117 }
118 if (error)
119 goto out;
120
121 error = -EINVAL;
122 if (!S_ISREG(nd.path.dentry->d_inode->i_mode))
123 goto exit;
124
125 error = -EACCES;
126 if (nd.path.mnt->mnt_flags & MNT_NOEXEC)
127 goto exit;
128
129 error = inode_permission(nd.path.dentry->d_inode,
130 MAY_READ | MAY_EXEC | MAY_OPEN);
131 if (error)
132 goto exit;
133
134 file = nameidata_to_filp(&nd, O_RDONLY|O_LARGEFILE);
135 error = PTR_ERR(file);
136 if (IS_ERR(file))
137 goto out;
138
139 fsnotify_open(file->f_path.dentry);
140
141 error = -ENOEXEC;
142 if(file->f_op) {
143 struct linux_binfmt * fmt;
144
145 read_lock(&binfmt_lock);
146 list_for_each_entry(fmt, &formats, lh) {
147 if (!fmt->load_shlib)
148 continue;
149 if (!try_module_get(fmt->module))
150 continue;
151 read_unlock(&binfmt_lock);
152 error = fmt->load_shlib(file);
153 read_lock(&binfmt_lock);
154 put_binfmt(fmt);
155 if (error != -ENOEXEC)
156 break;
157 }
158 read_unlock(&binfmt_lock);
159 }
160 fput(file);
161 out:
162 return error;
163 exit:
164 release_open_intent(&nd);
165 path_put(&nd.path);
166 goto out;
167 }
168
169 #ifdef CONFIG_MMU
170
get_arg_page(struct linux_binprm * bprm,unsigned long pos,int write)171 static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
172 int write)
173 {
174 struct page *page;
175 int ret;
176
177 #ifdef CONFIG_STACK_GROWSUP
178 if (write) {
179 ret = expand_stack_downwards(bprm->vma, pos);
180 if (ret < 0)
181 return NULL;
182 }
183 #endif
184 ret = get_user_pages(current, bprm->mm, pos,
185 1, write, 1, &page, NULL);
186 if (ret <= 0)
187 return NULL;
188
189 if (write) {
190 unsigned long size = bprm->vma->vm_end - bprm->vma->vm_start;
191 struct rlimit *rlim;
192
193 /*
194 * We've historically supported up to 32 pages (ARG_MAX)
195 * of argument strings even with small stacks
196 */
197 if (size <= ARG_MAX)
198 return page;
199
200 /*
201 * Limit to 1/4-th the stack size for the argv+env strings.
202 * This ensures that:
203 * - the remaining binfmt code will not run out of stack space,
204 * - the program will have a reasonable amount of stack left
205 * to work from.
206 */
207 rlim = current->signal->rlim;
208 if (size > rlim[RLIMIT_STACK].rlim_cur / 4) {
209 put_page(page);
210 return NULL;
211 }
212 }
213
214 return page;
215 }
216
put_arg_page(struct page * page)217 static void put_arg_page(struct page *page)
218 {
219 put_page(page);
220 }
221
free_arg_page(struct linux_binprm * bprm,int i)222 static void free_arg_page(struct linux_binprm *bprm, int i)
223 {
224 }
225
free_arg_pages(struct linux_binprm * bprm)226 static void free_arg_pages(struct linux_binprm *bprm)
227 {
228 }
229
flush_arg_page(struct linux_binprm * bprm,unsigned long pos,struct page * page)230 static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
231 struct page *page)
232 {
233 flush_cache_page(bprm->vma, pos, page_to_pfn(page));
234 }
235
__bprm_mm_init(struct linux_binprm * bprm)236 static int __bprm_mm_init(struct linux_binprm *bprm)
237 {
238 int err;
239 struct vm_area_struct *vma = NULL;
240 struct mm_struct *mm = bprm->mm;
241
242 bprm->vma = vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
243 if (!vma)
244 return -ENOMEM;
245
246 down_write(&mm->mmap_sem);
247 vma->vm_mm = mm;
248
249 /*
250 * Place the stack at the largest stack address the architecture
251 * supports. Later, we'll move this to an appropriate place. We don't
252 * use STACK_TOP because that can depend on attributes which aren't
253 * configured yet.
254 */
255 vma->vm_end = STACK_TOP_MAX;
256 vma->vm_start = vma->vm_end - PAGE_SIZE;
257 vma->vm_flags = VM_STACK_FLAGS;
258 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
259 err = insert_vm_struct(mm, vma);
260 if (err)
261 goto err;
262
263 mm->stack_vm = mm->total_vm = 1;
264 up_write(&mm->mmap_sem);
265 bprm->p = vma->vm_end - sizeof(void *);
266 return 0;
267 err:
268 up_write(&mm->mmap_sem);
269 bprm->vma = NULL;
270 kmem_cache_free(vm_area_cachep, vma);
271 return err;
272 }
273
valid_arg_len(struct linux_binprm * bprm,long len)274 static bool valid_arg_len(struct linux_binprm *bprm, long len)
275 {
276 return len <= MAX_ARG_STRLEN;
277 }
278
279 #else
280
get_arg_page(struct linux_binprm * bprm,unsigned long pos,int write)281 static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
282 int write)
283 {
284 struct page *page;
285
286 page = bprm->page[pos / PAGE_SIZE];
287 if (!page && write) {
288 page = alloc_page(GFP_HIGHUSER|__GFP_ZERO);
289 if (!page)
290 return NULL;
291 bprm->page[pos / PAGE_SIZE] = page;
292 }
293
294 return page;
295 }
296
put_arg_page(struct page * page)297 static void put_arg_page(struct page *page)
298 {
299 }
300
free_arg_page(struct linux_binprm * bprm,int i)301 static void free_arg_page(struct linux_binprm *bprm, int i)
302 {
303 if (bprm->page[i]) {
304 __free_page(bprm->page[i]);
305 bprm->page[i] = NULL;
306 }
307 }
308
free_arg_pages(struct linux_binprm * bprm)309 static void free_arg_pages(struct linux_binprm *bprm)
310 {
311 int i;
312
313 for (i = 0; i < MAX_ARG_PAGES; i++)
314 free_arg_page(bprm, i);
315 }
316
flush_arg_page(struct linux_binprm * bprm,unsigned long pos,struct page * page)317 static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
318 struct page *page)
319 {
320 }
321
__bprm_mm_init(struct linux_binprm * bprm)322 static int __bprm_mm_init(struct linux_binprm *bprm)
323 {
324 bprm->p = PAGE_SIZE * MAX_ARG_PAGES - sizeof(void *);
325 return 0;
326 }
327
valid_arg_len(struct linux_binprm * bprm,long len)328 static bool valid_arg_len(struct linux_binprm *bprm, long len)
329 {
330 return len <= bprm->p;
331 }
332
333 #endif /* CONFIG_MMU */
334
335 /*
336 * Create a new mm_struct and populate it with a temporary stack
337 * vm_area_struct. We don't have enough context at this point to set the stack
338 * flags, permissions, and offset, so we use temporary values. We'll update
339 * them later in setup_arg_pages().
340 */
bprm_mm_init(struct linux_binprm * bprm)341 int bprm_mm_init(struct linux_binprm *bprm)
342 {
343 int err;
344 struct mm_struct *mm = NULL;
345
346 bprm->mm = mm = mm_alloc();
347 err = -ENOMEM;
348 if (!mm)
349 goto err;
350
351 err = init_new_context(current, mm);
352 if (err)
353 goto err;
354
355 err = __bprm_mm_init(bprm);
356 if (err)
357 goto err;
358
359 return 0;
360
361 err:
362 if (mm) {
363 bprm->mm = NULL;
364 mmdrop(mm);
365 }
366
367 return err;
368 }
369
370 /*
371 * count() counts the number of strings in array ARGV.
372 */
count(char __user * __user * argv,int max)373 static int count(char __user * __user * argv, int max)
374 {
375 int i = 0;
376
377 if (argv != NULL) {
378 for (;;) {
379 char __user * p;
380
381 if (get_user(p, argv))
382 return -EFAULT;
383 if (!p)
384 break;
385 argv++;
386 if (i++ >= max)
387 return -E2BIG;
388 cond_resched();
389 }
390 }
391 return i;
392 }
393
394 /*
395 * 'copy_strings()' copies argument/environment strings from the old
396 * processes's memory to the new process's stack. The call to get_user_pages()
397 * ensures the destination page is created and not swapped out.
398 */
copy_strings(int argc,char __user * __user * argv,struct linux_binprm * bprm)399 static int copy_strings(int argc, char __user * __user * argv,
400 struct linux_binprm *bprm)
401 {
402 struct page *kmapped_page = NULL;
403 char *kaddr = NULL;
404 unsigned long kpos = 0;
405 int ret;
406
407 while (argc-- > 0) {
408 char __user *str;
409 int len;
410 unsigned long pos;
411
412 if (get_user(str, argv+argc) ||
413 !(len = strnlen_user(str, MAX_ARG_STRLEN))) {
414 ret = -EFAULT;
415 goto out;
416 }
417
418 if (!valid_arg_len(bprm, len)) {
419 ret = -E2BIG;
420 goto out;
421 }
422
423 /* We're going to work our way backwords. */
424 pos = bprm->p;
425 str += len;
426 bprm->p -= len;
427
428 while (len > 0) {
429 int offset, bytes_to_copy;
430
431 offset = pos % PAGE_SIZE;
432 if (offset == 0)
433 offset = PAGE_SIZE;
434
435 bytes_to_copy = offset;
436 if (bytes_to_copy > len)
437 bytes_to_copy = len;
438
439 offset -= bytes_to_copy;
440 pos -= bytes_to_copy;
441 str -= bytes_to_copy;
442 len -= bytes_to_copy;
443
444 if (!kmapped_page || kpos != (pos & PAGE_MASK)) {
445 struct page *page;
446
447 page = get_arg_page(bprm, pos, 1);
448 if (!page) {
449 ret = -E2BIG;
450 goto out;
451 }
452
453 if (kmapped_page) {
454 flush_kernel_dcache_page(kmapped_page);
455 kunmap(kmapped_page);
456 put_arg_page(kmapped_page);
457 }
458 kmapped_page = page;
459 kaddr = kmap(kmapped_page);
460 kpos = pos & PAGE_MASK;
461 flush_arg_page(bprm, kpos, kmapped_page);
462 }
463 if (copy_from_user(kaddr+offset, str, bytes_to_copy)) {
464 ret = -EFAULT;
465 goto out;
466 }
467 }
468 }
469 ret = 0;
470 out:
471 if (kmapped_page) {
472 flush_kernel_dcache_page(kmapped_page);
473 kunmap(kmapped_page);
474 put_arg_page(kmapped_page);
475 }
476 return ret;
477 }
478
479 /*
480 * Like copy_strings, but get argv and its values from kernel memory.
481 */
copy_strings_kernel(int argc,char ** argv,struct linux_binprm * bprm)482 int copy_strings_kernel(int argc,char ** argv, struct linux_binprm *bprm)
483 {
484 int r;
485 mm_segment_t oldfs = get_fs();
486 set_fs(KERNEL_DS);
487 r = copy_strings(argc, (char __user * __user *)argv, bprm);
488 set_fs(oldfs);
489 return r;
490 }
491 EXPORT_SYMBOL(copy_strings_kernel);
492
493 #ifdef CONFIG_MMU
494
495 /*
496 * During bprm_mm_init(), we create a temporary stack at STACK_TOP_MAX. Once
497 * the binfmt code determines where the new stack should reside, we shift it to
498 * its final location. The process proceeds as follows:
499 *
500 * 1) Use shift to calculate the new vma endpoints.
501 * 2) Extend vma to cover both the old and new ranges. This ensures the
502 * arguments passed to subsequent functions are consistent.
503 * 3) Move vma's page tables to the new range.
504 * 4) Free up any cleared pgd range.
505 * 5) Shrink the vma to cover only the new range.
506 */
shift_arg_pages(struct vm_area_struct * vma,unsigned long shift)507 static int shift_arg_pages(struct vm_area_struct *vma, unsigned long shift)
508 {
509 struct mm_struct *mm = vma->vm_mm;
510 unsigned long old_start = vma->vm_start;
511 unsigned long old_end = vma->vm_end;
512 unsigned long length = old_end - old_start;
513 unsigned long new_start = old_start - shift;
514 unsigned long new_end = old_end - shift;
515 struct mmu_gather *tlb;
516
517 BUG_ON(new_start > new_end);
518
519 /*
520 * ensure there are no vmas between where we want to go
521 * and where we are
522 */
523 if (vma != find_vma(mm, new_start))
524 return -EFAULT;
525
526 /*
527 * cover the whole range: [new_start, old_end)
528 */
529 vma_adjust(vma, new_start, old_end, vma->vm_pgoff, NULL);
530
531 /*
532 * move the page tables downwards, on failure we rely on
533 * process cleanup to remove whatever mess we made.
534 */
535 if (length != move_page_tables(vma, old_start,
536 vma, new_start, length))
537 return -ENOMEM;
538
539 lru_add_drain();
540 tlb = tlb_gather_mmu(mm, 0);
541 if (new_end > old_start) {
542 /*
543 * when the old and new regions overlap clear from new_end.
544 */
545 free_pgd_range(tlb, new_end, old_end, new_end,
546 vma->vm_next ? vma->vm_next->vm_start : 0);
547 } else {
548 /*
549 * otherwise, clean from old_start; this is done to not touch
550 * the address space in [new_end, old_start) some architectures
551 * have constraints on va-space that make this illegal (IA64) -
552 * for the others its just a little faster.
553 */
554 free_pgd_range(tlb, old_start, old_end, new_end,
555 vma->vm_next ? vma->vm_next->vm_start : 0);
556 }
557 tlb_finish_mmu(tlb, new_end, old_end);
558
559 /*
560 * shrink the vma to just the new range.
561 */
562 vma_adjust(vma, new_start, new_end, vma->vm_pgoff, NULL);
563
564 return 0;
565 }
566
567 #define EXTRA_STACK_VM_PAGES 20 /* random */
568
569 /*
570 * Finalizes the stack vm_area_struct. The flags and permissions are updated,
571 * the stack is optionally relocated, and some extra space is added.
572 */
setup_arg_pages(struct linux_binprm * bprm,unsigned long stack_top,int executable_stack)573 int setup_arg_pages(struct linux_binprm *bprm,
574 unsigned long stack_top,
575 int executable_stack)
576 {
577 unsigned long ret;
578 unsigned long stack_shift;
579 struct mm_struct *mm = current->mm;
580 struct vm_area_struct *vma = bprm->vma;
581 struct vm_area_struct *prev = NULL;
582 unsigned long vm_flags;
583 unsigned long stack_base;
584
585 #ifdef CONFIG_STACK_GROWSUP
586 /* Limit stack size to 1GB */
587 stack_base = current->signal->rlim[RLIMIT_STACK].rlim_max;
588 if (stack_base > (1 << 30))
589 stack_base = 1 << 30;
590
591 /* Make sure we didn't let the argument array grow too large. */
592 if (vma->vm_end - vma->vm_start > stack_base)
593 return -ENOMEM;
594
595 stack_base = PAGE_ALIGN(stack_top - stack_base);
596
597 stack_shift = vma->vm_start - stack_base;
598 mm->arg_start = bprm->p - stack_shift;
599 bprm->p = vma->vm_end - stack_shift;
600 #else
601 stack_top = arch_align_stack(stack_top);
602 stack_top = PAGE_ALIGN(stack_top);
603 stack_shift = vma->vm_end - stack_top;
604
605 bprm->p -= stack_shift;
606 mm->arg_start = bprm->p;
607 #endif
608
609 if (bprm->loader)
610 bprm->loader -= stack_shift;
611 bprm->exec -= stack_shift;
612
613 down_write(&mm->mmap_sem);
614 vm_flags = VM_STACK_FLAGS;
615
616 /*
617 * Adjust stack execute permissions; explicitly enable for
618 * EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X and leave alone
619 * (arch default) otherwise.
620 */
621 if (unlikely(executable_stack == EXSTACK_ENABLE_X))
622 vm_flags |= VM_EXEC;
623 else if (executable_stack == EXSTACK_DISABLE_X)
624 vm_flags &= ~VM_EXEC;
625 vm_flags |= mm->def_flags;
626
627 ret = mprotect_fixup(vma, &prev, vma->vm_start, vma->vm_end,
628 vm_flags);
629 if (ret)
630 goto out_unlock;
631 BUG_ON(prev != vma);
632
633 /* Move stack pages down in memory. */
634 if (stack_shift) {
635 ret = shift_arg_pages(vma, stack_shift);
636 if (ret) {
637 up_write(&mm->mmap_sem);
638 return ret;
639 }
640 }
641
642 #ifdef CONFIG_STACK_GROWSUP
643 stack_base = vma->vm_end + EXTRA_STACK_VM_PAGES * PAGE_SIZE;
644 #else
645 stack_base = vma->vm_start - EXTRA_STACK_VM_PAGES * PAGE_SIZE;
646 #endif
647 ret = expand_stack(vma, stack_base);
648 if (ret)
649 ret = -EFAULT;
650
651 out_unlock:
652 up_write(&mm->mmap_sem);
653 return 0;
654 }
655 EXPORT_SYMBOL(setup_arg_pages);
656
657 #endif /* CONFIG_MMU */
658
open_exec(const char * name)659 struct file *open_exec(const char *name)
660 {
661 struct nameidata nd;
662 struct file *file;
663 int err;
664
665 err = path_lookup_open(AT_FDCWD, name, LOOKUP_FOLLOW, &nd,
666 FMODE_READ|FMODE_EXEC);
667 if (err)
668 goto out;
669
670 err = -EACCES;
671 if (!S_ISREG(nd.path.dentry->d_inode->i_mode))
672 goto out_path_put;
673
674 if (nd.path.mnt->mnt_flags & MNT_NOEXEC)
675 goto out_path_put;
676
677 err = inode_permission(nd.path.dentry->d_inode, MAY_EXEC | MAY_OPEN);
678 if (err)
679 goto out_path_put;
680
681 file = nameidata_to_filp(&nd, O_RDONLY|O_LARGEFILE);
682 if (IS_ERR(file))
683 return file;
684
685 fsnotify_open(file->f_path.dentry);
686
687 err = deny_write_access(file);
688 if (err) {
689 fput(file);
690 goto out;
691 }
692
693 return file;
694
695 out_path_put:
696 release_open_intent(&nd);
697 path_put(&nd.path);
698 out:
699 return ERR_PTR(err);
700 }
701 EXPORT_SYMBOL(open_exec);
702
kernel_read(struct file * file,unsigned long offset,char * addr,unsigned long count)703 int kernel_read(struct file *file, unsigned long offset,
704 char *addr, unsigned long count)
705 {
706 mm_segment_t old_fs;
707 loff_t pos = offset;
708 int result;
709
710 old_fs = get_fs();
711 set_fs(get_ds());
712 /* The cast to a user pointer is valid due to the set_fs() */
713 result = vfs_read(file, (void __user *)addr, count, &pos);
714 set_fs(old_fs);
715 return result;
716 }
717
718 EXPORT_SYMBOL(kernel_read);
719
exec_mmap(struct mm_struct * mm)720 static int exec_mmap(struct mm_struct *mm)
721 {
722 struct task_struct *tsk;
723 struct mm_struct * old_mm, *active_mm;
724
725 /* Notify parent that we're no longer interested in the old VM */
726 tsk = current;
727 old_mm = current->mm;
728 mm_release(tsk, old_mm);
729
730 if (old_mm) {
731 /*
732 * Make sure that if there is a core dump in progress
733 * for the old mm, we get out and die instead of going
734 * through with the exec. We must hold mmap_sem around
735 * checking core_state and changing tsk->mm.
736 */
737 down_read(&old_mm->mmap_sem);
738 if (unlikely(old_mm->core_state)) {
739 up_read(&old_mm->mmap_sem);
740 return -EINTR;
741 }
742 }
743 task_lock(tsk);
744 active_mm = tsk->active_mm;
745 tsk->mm = mm;
746 tsk->active_mm = mm;
747 activate_mm(active_mm, mm);
748 task_unlock(tsk);
749 arch_pick_mmap_layout(mm);
750 if (old_mm) {
751 up_read(&old_mm->mmap_sem);
752 BUG_ON(active_mm != old_mm);
753 mm_update_next_owner(old_mm);
754 mmput(old_mm);
755 return 0;
756 }
757 mmdrop(active_mm);
758 return 0;
759 }
760
761 /*
762 * This function makes sure the current process has its own signal table,
763 * so that flush_signal_handlers can later reset the handlers without
764 * disturbing other processes. (Other processes might share the signal
765 * table via the CLONE_SIGHAND option to clone().)
766 */
de_thread(struct task_struct * tsk)767 static int de_thread(struct task_struct *tsk)
768 {
769 struct signal_struct *sig = tsk->signal;
770 struct sighand_struct *oldsighand = tsk->sighand;
771 spinlock_t *lock = &oldsighand->siglock;
772 int count;
773
774 if (thread_group_empty(tsk))
775 goto no_thread_group;
776
777 /*
778 * Kill all other threads in the thread group.
779 */
780 spin_lock_irq(lock);
781 if (signal_group_exit(sig)) {
782 /*
783 * Another group action in progress, just
784 * return so that the signal is processed.
785 */
786 spin_unlock_irq(lock);
787 return -EAGAIN;
788 }
789 sig->group_exit_task = tsk;
790 zap_other_threads(tsk);
791
792 /* Account for the thread group leader hanging around: */
793 count = thread_group_leader(tsk) ? 1 : 2;
794 sig->notify_count = count;
795 while (atomic_read(&sig->count) > count) {
796 __set_current_state(TASK_UNINTERRUPTIBLE);
797 spin_unlock_irq(lock);
798 schedule();
799 spin_lock_irq(lock);
800 }
801 spin_unlock_irq(lock);
802
803 /*
804 * At this point all other threads have exited, all we have to
805 * do is to wait for the thread group leader to become inactive,
806 * and to assume its PID:
807 */
808 if (!thread_group_leader(tsk)) {
809 struct task_struct *leader = tsk->group_leader;
810
811 sig->notify_count = -1; /* for exit_notify() */
812 for (;;) {
813 write_lock_irq(&tasklist_lock);
814 if (likely(leader->exit_state))
815 break;
816 __set_current_state(TASK_UNINTERRUPTIBLE);
817 write_unlock_irq(&tasklist_lock);
818 schedule();
819 }
820
821 /*
822 * The only record we have of the real-time age of a
823 * process, regardless of execs it's done, is start_time.
824 * All the past CPU time is accumulated in signal_struct
825 * from sister threads now dead. But in this non-leader
826 * exec, nothing survives from the original leader thread,
827 * whose birth marks the true age of this process now.
828 * When we take on its identity by switching to its PID, we
829 * also take its birthdate (always earlier than our own).
830 */
831 tsk->start_time = leader->start_time;
832
833 BUG_ON(!same_thread_group(leader, tsk));
834 BUG_ON(has_group_leader_pid(tsk));
835 /*
836 * An exec() starts a new thread group with the
837 * TGID of the previous thread group. Rehash the
838 * two threads with a switched PID, and release
839 * the former thread group leader:
840 */
841
842 /* Become a process group leader with the old leader's pid.
843 * The old leader becomes a thread of the this thread group.
844 * Note: The old leader also uses this pid until release_task
845 * is called. Odd but simple and correct.
846 */
847 detach_pid(tsk, PIDTYPE_PID);
848 tsk->pid = leader->pid;
849 attach_pid(tsk, PIDTYPE_PID, task_pid(leader));
850 transfer_pid(leader, tsk, PIDTYPE_PGID);
851 transfer_pid(leader, tsk, PIDTYPE_SID);
852 list_replace_rcu(&leader->tasks, &tsk->tasks);
853
854 tsk->group_leader = tsk;
855 leader->group_leader = tsk;
856
857 tsk->exit_signal = SIGCHLD;
858
859 BUG_ON(leader->exit_state != EXIT_ZOMBIE);
860 leader->exit_state = EXIT_DEAD;
861 write_unlock_irq(&tasklist_lock);
862
863 release_task(leader);
864 }
865
866 sig->group_exit_task = NULL;
867 sig->notify_count = 0;
868
869 no_thread_group:
870 exit_itimers(sig);
871 flush_itimer_signals();
872
873 if (atomic_read(&oldsighand->count) != 1) {
874 struct sighand_struct *newsighand;
875 /*
876 * This ->sighand is shared with the CLONE_SIGHAND
877 * but not CLONE_THREAD task, switch to the new one.
878 */
879 newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
880 if (!newsighand)
881 return -ENOMEM;
882
883 atomic_set(&newsighand->count, 1);
884 memcpy(newsighand->action, oldsighand->action,
885 sizeof(newsighand->action));
886
887 write_lock_irq(&tasklist_lock);
888 spin_lock(&oldsighand->siglock);
889 rcu_assign_pointer(tsk->sighand, newsighand);
890 spin_unlock(&oldsighand->siglock);
891 write_unlock_irq(&tasklist_lock);
892
893 __cleanup_sighand(oldsighand);
894 }
895
896 BUG_ON(!thread_group_leader(tsk));
897 return 0;
898 }
899
900 /*
901 * These functions flushes out all traces of the currently running executable
902 * so that a new one can be started
903 */
flush_old_files(struct files_struct * files)904 static void flush_old_files(struct files_struct * files)
905 {
906 long j = -1;
907 struct fdtable *fdt;
908
909 spin_lock(&files->file_lock);
910 for (;;) {
911 unsigned long set, i;
912
913 j++;
914 i = j * __NFDBITS;
915 fdt = files_fdtable(files);
916 if (i >= fdt->max_fds)
917 break;
918 set = fdt->close_on_exec->fds_bits[j];
919 if (!set)
920 continue;
921 fdt->close_on_exec->fds_bits[j] = 0;
922 spin_unlock(&files->file_lock);
923 for ( ; set ; i++,set >>= 1) {
924 if (set & 1) {
925 sys_close(i);
926 }
927 }
928 spin_lock(&files->file_lock);
929
930 }
931 spin_unlock(&files->file_lock);
932 }
933
get_task_comm(char * buf,struct task_struct * tsk)934 char *get_task_comm(char *buf, struct task_struct *tsk)
935 {
936 /* buf must be at least sizeof(tsk->comm) in size */
937 task_lock(tsk);
938 strncpy(buf, tsk->comm, sizeof(tsk->comm));
939 task_unlock(tsk);
940 return buf;
941 }
942
set_task_comm(struct task_struct * tsk,char * buf)943 void set_task_comm(struct task_struct *tsk, char *buf)
944 {
945 task_lock(tsk);
946 strlcpy(tsk->comm, buf, sizeof(tsk->comm));
947 task_unlock(tsk);
948 #ifdef CONFIG_QEMU_TRACE
949 qemu_trace_thread_name(buf);
950 #endif
951 }
952
flush_old_exec(struct linux_binprm * bprm)953 int flush_old_exec(struct linux_binprm * bprm)
954 {
955 char * name;
956 int i, ch, retval;
957 char tcomm[sizeof(current->comm)];
958
959 /*
960 * Make sure we have a private signal table and that
961 * we are unassociated from the previous thread group.
962 */
963 retval = de_thread(current);
964 if (retval)
965 goto out;
966
967 set_mm_exe_file(bprm->mm, bprm->file);
968
969 /*
970 * Release all of the old mmap stuff
971 */
972 retval = exec_mmap(bprm->mm);
973 if (retval)
974 goto out;
975
976 bprm->mm = NULL; /* We're using it now */
977
978 /* This is the point of no return */
979 current->sas_ss_sp = current->sas_ss_size = 0;
980
981 if (current_euid() == current_uid() && current_egid() == current_gid())
982 set_dumpable(current->mm, 1);
983 else
984 set_dumpable(current->mm, suid_dumpable);
985
986 name = bprm->filename;
987
988 /* Copies the binary name from after last slash */
989 for (i=0; (ch = *(name++)) != '\0';) {
990 if (ch == '/')
991 i = 0; /* overwrite what we wrote */
992 else
993 if (i < (sizeof(tcomm) - 1))
994 tcomm[i++] = ch;
995 }
996 tcomm[i] = '\0';
997 set_task_comm(current, tcomm);
998
999 current->flags &= ~PF_RANDOMIZE;
1000 flush_thread();
1001
1002 /* Set the new mm task size. We have to do that late because it may
1003 * depend on TIF_32BIT which is only updated in flush_thread() on
1004 * some architectures like powerpc
1005 */
1006 current->mm->task_size = TASK_SIZE;
1007
1008 /* install the new credentials */
1009 if (bprm->cred->uid != current_euid() ||
1010 bprm->cred->gid != current_egid()) {
1011 current->pdeath_signal = 0;
1012 } else if (file_permission(bprm->file, MAY_READ) ||
1013 bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP) {
1014 set_dumpable(current->mm, suid_dumpable);
1015 }
1016
1017 current->personality &= ~bprm->per_clear;
1018
1019 /* An exec changes our domain. We are no longer part of the thread
1020 group */
1021
1022 current->self_exec_id++;
1023
1024 flush_signal_handlers(current, 0);
1025 flush_old_files(current->files);
1026
1027 return 0;
1028
1029 out:
1030 return retval;
1031 }
1032
1033 EXPORT_SYMBOL(flush_old_exec);
1034
1035 /*
1036 * install the new credentials for this executable
1037 */
install_exec_creds(struct linux_binprm * bprm)1038 void install_exec_creds(struct linux_binprm *bprm)
1039 {
1040 security_bprm_committing_creds(bprm);
1041
1042 commit_creds(bprm->cred);
1043 bprm->cred = NULL;
1044
1045 /* cred_exec_mutex must be held at least to this point to prevent
1046 * ptrace_attach() from altering our determination of the task's
1047 * credentials; any time after this it may be unlocked */
1048
1049 security_bprm_committed_creds(bprm);
1050 }
1051 EXPORT_SYMBOL(install_exec_creds);
1052
1053 /*
1054 * determine how safe it is to execute the proposed program
1055 * - the caller must hold current->cred_exec_mutex to protect against
1056 * PTRACE_ATTACH
1057 */
check_unsafe_exec(struct linux_binprm * bprm,struct files_struct * files)1058 void check_unsafe_exec(struct linux_binprm *bprm, struct files_struct *files)
1059 {
1060 struct task_struct *p = current, *t;
1061 unsigned long flags;
1062 unsigned n_fs, n_files, n_sighand;
1063
1064 bprm->unsafe = tracehook_unsafe_exec(p);
1065
1066 n_fs = 1;
1067 n_files = 1;
1068 n_sighand = 1;
1069 lock_task_sighand(p, &flags);
1070 for (t = next_thread(p); t != p; t = next_thread(t)) {
1071 if (t->fs == p->fs)
1072 n_fs++;
1073 if (t->files == files)
1074 n_files++;
1075 n_sighand++;
1076 }
1077
1078 if (atomic_read(&p->fs->count) > n_fs ||
1079 atomic_read(&p->files->count) > n_files ||
1080 atomic_read(&p->sighand->count) > n_sighand)
1081 bprm->unsafe |= LSM_UNSAFE_SHARE;
1082
1083 unlock_task_sighand(p, &flags);
1084 }
1085
1086 /*
1087 * Fill the binprm structure from the inode.
1088 * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
1089 *
1090 * This may be called multiple times for binary chains (scripts for example).
1091 */
prepare_binprm(struct linux_binprm * bprm)1092 int prepare_binprm(struct linux_binprm *bprm)
1093 {
1094 umode_t mode;
1095 struct inode * inode = bprm->file->f_path.dentry->d_inode;
1096 int retval;
1097
1098 mode = inode->i_mode;
1099 if (bprm->file->f_op == NULL)
1100 return -EACCES;
1101
1102 /* clear any previous set[ug]id data from a previous binary */
1103 bprm->cred->euid = current_euid();
1104 bprm->cred->egid = current_egid();
1105
1106 if (!(bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID)) {
1107 /* Set-uid? */
1108 if (mode & S_ISUID) {
1109 bprm->per_clear |= PER_CLEAR_ON_SETID;
1110 bprm->cred->euid = inode->i_uid;
1111 }
1112
1113 /* Set-gid? */
1114 /*
1115 * If setgid is set but no group execute bit then this
1116 * is a candidate for mandatory locking, not a setgid
1117 * executable.
1118 */
1119 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
1120 bprm->per_clear |= PER_CLEAR_ON_SETID;
1121 bprm->cred->egid = inode->i_gid;
1122 }
1123 }
1124
1125 /* fill in binprm security blob */
1126 retval = security_bprm_set_creds(bprm);
1127 if (retval)
1128 return retval;
1129 bprm->cred_prepared = 1;
1130
1131 memset(bprm->buf, 0, BINPRM_BUF_SIZE);
1132 return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
1133 }
1134
1135 EXPORT_SYMBOL(prepare_binprm);
1136
1137 /*
1138 * Arguments are '\0' separated strings found at the location bprm->p
1139 * points to; chop off the first by relocating brpm->p to right after
1140 * the first '\0' encountered.
1141 */
remove_arg_zero(struct linux_binprm * bprm)1142 int remove_arg_zero(struct linux_binprm *bprm)
1143 {
1144 int ret = 0;
1145 unsigned long offset;
1146 char *kaddr;
1147 struct page *page;
1148
1149 if (!bprm->argc)
1150 return 0;
1151
1152 do {
1153 offset = bprm->p & ~PAGE_MASK;
1154 page = get_arg_page(bprm, bprm->p, 0);
1155 if (!page) {
1156 ret = -EFAULT;
1157 goto out;
1158 }
1159 kaddr = kmap_atomic(page, KM_USER0);
1160
1161 for (; offset < PAGE_SIZE && kaddr[offset];
1162 offset++, bprm->p++)
1163 ;
1164
1165 kunmap_atomic(kaddr, KM_USER0);
1166 put_arg_page(page);
1167
1168 if (offset == PAGE_SIZE)
1169 free_arg_page(bprm, (bprm->p >> PAGE_SHIFT) - 1);
1170 } while (offset == PAGE_SIZE);
1171
1172 bprm->p++;
1173 bprm->argc--;
1174 ret = 0;
1175
1176 out:
1177 return ret;
1178 }
1179 EXPORT_SYMBOL(remove_arg_zero);
1180
1181 /*
1182 * cycle the list of binary formats handler, until one recognizes the image
1183 */
search_binary_handler(struct linux_binprm * bprm,struct pt_regs * regs)1184 int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs)
1185 {
1186 unsigned int depth = bprm->recursion_depth;
1187 int try,retval;
1188 struct linux_binfmt *fmt;
1189
1190 retval = security_bprm_check(bprm);
1191 if (retval)
1192 return retval;
1193
1194 /* kernel module loader fixup */
1195 /* so we don't try to load run modprobe in kernel space. */
1196 set_fs(USER_DS);
1197
1198 retval = audit_bprm(bprm);
1199 if (retval)
1200 return retval;
1201
1202 retval = -ENOENT;
1203 for (try=0; try<2; try++) {
1204 read_lock(&binfmt_lock);
1205 list_for_each_entry(fmt, &formats, lh) {
1206 int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
1207 if (!fn)
1208 continue;
1209 if (!try_module_get(fmt->module))
1210 continue;
1211 read_unlock(&binfmt_lock);
1212 retval = fn(bprm, regs);
1213 /*
1214 * Restore the depth counter to its starting value
1215 * in this call, so we don't have to rely on every
1216 * load_binary function to restore it on return.
1217 */
1218 bprm->recursion_depth = depth;
1219 if (retval >= 0) {
1220 if (depth == 0)
1221 tracehook_report_exec(fmt, bprm, regs);
1222 put_binfmt(fmt);
1223 allow_write_access(bprm->file);
1224 if (bprm->file)
1225 fput(bprm->file);
1226 bprm->file = NULL;
1227 current->did_exec = 1;
1228 proc_exec_connector(current);
1229 return retval;
1230 }
1231 read_lock(&binfmt_lock);
1232 put_binfmt(fmt);
1233 if (retval != -ENOEXEC || bprm->mm == NULL)
1234 break;
1235 if (!bprm->file) {
1236 read_unlock(&binfmt_lock);
1237 return retval;
1238 }
1239 }
1240 read_unlock(&binfmt_lock);
1241 if (retval != -ENOEXEC || bprm->mm == NULL) {
1242 break;
1243 #ifdef CONFIG_MODULES
1244 } else {
1245 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
1246 if (printable(bprm->buf[0]) &&
1247 printable(bprm->buf[1]) &&
1248 printable(bprm->buf[2]) &&
1249 printable(bprm->buf[3]))
1250 break; /* -ENOEXEC */
1251 request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
1252 #endif
1253 }
1254 }
1255 return retval;
1256 }
1257
1258 EXPORT_SYMBOL(search_binary_handler);
1259
free_bprm(struct linux_binprm * bprm)1260 void free_bprm(struct linux_binprm *bprm)
1261 {
1262 free_arg_pages(bprm);
1263 if (bprm->cred)
1264 abort_creds(bprm->cred);
1265 kfree(bprm);
1266 }
1267
1268 #ifdef CONFIG_QEMU_TRACE
1269 extern void qemu_trace_execve(int argc, char __user * __user * argv);
1270 #endif
1271
1272 /*
1273 * sys_execve() executes a new program.
1274 */
do_execve(char * filename,char __user * __user * argv,char __user * __user * envp,struct pt_regs * regs)1275 int do_execve(char * filename,
1276 char __user *__user *argv,
1277 char __user *__user *envp,
1278 struct pt_regs * regs)
1279 {
1280 struct linux_binprm *bprm;
1281 struct file *file;
1282 struct files_struct *displaced;
1283 int retval;
1284
1285 retval = unshare_files(&displaced);
1286 if (retval)
1287 goto out_ret;
1288
1289 retval = -ENOMEM;
1290 bprm = kzalloc(sizeof(*bprm), GFP_KERNEL);
1291 if (!bprm)
1292 goto out_files;
1293
1294 retval = mutex_lock_interruptible(¤t->cred_exec_mutex);
1295 if (retval < 0)
1296 goto out_free;
1297
1298 retval = -ENOMEM;
1299 bprm->cred = prepare_exec_creds();
1300 if (!bprm->cred)
1301 goto out_unlock;
1302 check_unsafe_exec(bprm, displaced);
1303
1304 file = open_exec(filename);
1305 retval = PTR_ERR(file);
1306 if (IS_ERR(file))
1307 goto out_unlock;
1308
1309 sched_exec();
1310
1311 bprm->file = file;
1312 bprm->filename = filename;
1313 bprm->interp = filename;
1314
1315 retval = bprm_mm_init(bprm);
1316 if (retval)
1317 goto out_file;
1318
1319 bprm->argc = count(argv, MAX_ARG_STRINGS);
1320 if ((retval = bprm->argc) < 0)
1321 goto out;
1322
1323 bprm->envc = count(envp, MAX_ARG_STRINGS);
1324 if ((retval = bprm->envc) < 0)
1325 goto out;
1326
1327 retval = prepare_binprm(bprm);
1328 if (retval < 0)
1329 goto out;
1330
1331 retval = copy_strings_kernel(1, &bprm->filename, bprm);
1332 if (retval < 0)
1333 goto out;
1334
1335 bprm->exec = bprm->p;
1336 retval = copy_strings(bprm->envc, envp, bprm);
1337 if (retval < 0)
1338 goto out;
1339
1340 retval = copy_strings(bprm->argc, argv, bprm);
1341 if (retval < 0)
1342 goto out;
1343
1344 current->flags &= ~PF_KTHREAD;
1345 #ifdef CONFIG_QEMU_TRACE
1346 qemu_trace_execve(bprm->argc, argv);
1347 #endif
1348
1349 retval = search_binary_handler(bprm,regs);
1350 if (retval < 0)
1351 goto out;
1352
1353 /* execve succeeded */
1354 mutex_unlock(¤t->cred_exec_mutex);
1355 acct_update_integrals(current);
1356 free_bprm(bprm);
1357 if (displaced)
1358 put_files_struct(displaced);
1359 return retval;
1360
1361 out:
1362 if (bprm->mm)
1363 mmput (bprm->mm);
1364
1365 out_file:
1366 if (bprm->file) {
1367 allow_write_access(bprm->file);
1368 fput(bprm->file);
1369 }
1370
1371 out_unlock:
1372 mutex_unlock(¤t->cred_exec_mutex);
1373
1374 out_free:
1375 free_bprm(bprm);
1376
1377 out_files:
1378 if (displaced)
1379 reset_files_struct(displaced);
1380 out_ret:
1381 return retval;
1382 }
1383
set_binfmt(struct linux_binfmt * new)1384 int set_binfmt(struct linux_binfmt *new)
1385 {
1386 struct linux_binfmt *old = current->binfmt;
1387
1388 if (new) {
1389 if (!try_module_get(new->module))
1390 return -1;
1391 }
1392 current->binfmt = new;
1393 if (old)
1394 module_put(old->module);
1395 return 0;
1396 }
1397
1398 EXPORT_SYMBOL(set_binfmt);
1399
1400 /* format_corename will inspect the pattern parameter, and output a
1401 * name into corename, which must have space for at least
1402 * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
1403 */
format_corename(char * corename,long signr)1404 static int format_corename(char *corename, long signr)
1405 {
1406 const struct cred *cred = current_cred();
1407 const char *pat_ptr = core_pattern;
1408 int ispipe = (*pat_ptr == '|');
1409 char *out_ptr = corename;
1410 char *const out_end = corename + CORENAME_MAX_SIZE;
1411 int rc;
1412 int pid_in_pattern = 0;
1413
1414 /* Repeat as long as we have more pattern to process and more output
1415 space */
1416 while (*pat_ptr) {
1417 if (*pat_ptr != '%') {
1418 if (out_ptr == out_end)
1419 goto out;
1420 *out_ptr++ = *pat_ptr++;
1421 } else {
1422 switch (*++pat_ptr) {
1423 case 0:
1424 goto out;
1425 /* Double percent, output one percent */
1426 case '%':
1427 if (out_ptr == out_end)
1428 goto out;
1429 *out_ptr++ = '%';
1430 break;
1431 /* pid */
1432 case 'p':
1433 pid_in_pattern = 1;
1434 rc = snprintf(out_ptr, out_end - out_ptr,
1435 "%d", task_tgid_vnr(current));
1436 if (rc > out_end - out_ptr)
1437 goto out;
1438 out_ptr += rc;
1439 break;
1440 /* uid */
1441 case 'u':
1442 rc = snprintf(out_ptr, out_end - out_ptr,
1443 "%d", cred->uid);
1444 if (rc > out_end - out_ptr)
1445 goto out;
1446 out_ptr += rc;
1447 break;
1448 /* gid */
1449 case 'g':
1450 rc = snprintf(out_ptr, out_end - out_ptr,
1451 "%d", cred->gid);
1452 if (rc > out_end - out_ptr)
1453 goto out;
1454 out_ptr += rc;
1455 break;
1456 /* signal that caused the coredump */
1457 case 's':
1458 rc = snprintf(out_ptr, out_end - out_ptr,
1459 "%ld", signr);
1460 if (rc > out_end - out_ptr)
1461 goto out;
1462 out_ptr += rc;
1463 break;
1464 /* UNIX time of coredump */
1465 case 't': {
1466 struct timeval tv;
1467 do_gettimeofday(&tv);
1468 rc = snprintf(out_ptr, out_end - out_ptr,
1469 "%lu", tv.tv_sec);
1470 if (rc > out_end - out_ptr)
1471 goto out;
1472 out_ptr += rc;
1473 break;
1474 }
1475 /* hostname */
1476 case 'h':
1477 down_read(&uts_sem);
1478 rc = snprintf(out_ptr, out_end - out_ptr,
1479 "%s", utsname()->nodename);
1480 up_read(&uts_sem);
1481 if (rc > out_end - out_ptr)
1482 goto out;
1483 out_ptr += rc;
1484 break;
1485 /* executable */
1486 case 'e':
1487 rc = snprintf(out_ptr, out_end - out_ptr,
1488 "%s", current->comm);
1489 if (rc > out_end - out_ptr)
1490 goto out;
1491 out_ptr += rc;
1492 break;
1493 /* core limit size */
1494 case 'c':
1495 rc = snprintf(out_ptr, out_end - out_ptr,
1496 "%lu", current->signal->rlim[RLIMIT_CORE].rlim_cur);
1497 if (rc > out_end - out_ptr)
1498 goto out;
1499 out_ptr += rc;
1500 break;
1501 default:
1502 break;
1503 }
1504 ++pat_ptr;
1505 }
1506 }
1507 /* Backward compatibility with core_uses_pid:
1508 *
1509 * If core_pattern does not include a %p (as is the default)
1510 * and core_uses_pid is set, then .%pid will be appended to
1511 * the filename. Do not do this for piped commands. */
1512 if (!ispipe && !pid_in_pattern && core_uses_pid) {
1513 rc = snprintf(out_ptr, out_end - out_ptr,
1514 ".%d", task_tgid_vnr(current));
1515 if (rc > out_end - out_ptr)
1516 goto out;
1517 out_ptr += rc;
1518 }
1519 out:
1520 *out_ptr = 0;
1521 return ispipe;
1522 }
1523
zap_process(struct task_struct * start)1524 static int zap_process(struct task_struct *start)
1525 {
1526 struct task_struct *t;
1527 int nr = 0;
1528
1529 start->signal->flags = SIGNAL_GROUP_EXIT;
1530 start->signal->group_stop_count = 0;
1531
1532 t = start;
1533 do {
1534 if (t != current && t->mm) {
1535 sigaddset(&t->pending.signal, SIGKILL);
1536 signal_wake_up(t, 1);
1537 nr++;
1538 }
1539 } while_each_thread(start, t);
1540
1541 return nr;
1542 }
1543
zap_threads(struct task_struct * tsk,struct mm_struct * mm,struct core_state * core_state,int exit_code)1544 static inline int zap_threads(struct task_struct *tsk, struct mm_struct *mm,
1545 struct core_state *core_state, int exit_code)
1546 {
1547 struct task_struct *g, *p;
1548 unsigned long flags;
1549 int nr = -EAGAIN;
1550
1551 spin_lock_irq(&tsk->sighand->siglock);
1552 if (!signal_group_exit(tsk->signal)) {
1553 mm->core_state = core_state;
1554 tsk->signal->group_exit_code = exit_code;
1555 nr = zap_process(tsk);
1556 }
1557 spin_unlock_irq(&tsk->sighand->siglock);
1558 if (unlikely(nr < 0))
1559 return nr;
1560
1561 if (atomic_read(&mm->mm_users) == nr + 1)
1562 goto done;
1563 /*
1564 * We should find and kill all tasks which use this mm, and we should
1565 * count them correctly into ->nr_threads. We don't take tasklist
1566 * lock, but this is safe wrt:
1567 *
1568 * fork:
1569 * None of sub-threads can fork after zap_process(leader). All
1570 * processes which were created before this point should be
1571 * visible to zap_threads() because copy_process() adds the new
1572 * process to the tail of init_task.tasks list, and lock/unlock
1573 * of ->siglock provides a memory barrier.
1574 *
1575 * do_exit:
1576 * The caller holds mm->mmap_sem. This means that the task which
1577 * uses this mm can't pass exit_mm(), so it can't exit or clear
1578 * its ->mm.
1579 *
1580 * de_thread:
1581 * It does list_replace_rcu(&leader->tasks, ¤t->tasks),
1582 * we must see either old or new leader, this does not matter.
1583 * However, it can change p->sighand, so lock_task_sighand(p)
1584 * must be used. Since p->mm != NULL and we hold ->mmap_sem
1585 * it can't fail.
1586 *
1587 * Note also that "g" can be the old leader with ->mm == NULL
1588 * and already unhashed and thus removed from ->thread_group.
1589 * This is OK, __unhash_process()->list_del_rcu() does not
1590 * clear the ->next pointer, we will find the new leader via
1591 * next_thread().
1592 */
1593 rcu_read_lock();
1594 for_each_process(g) {
1595 if (g == tsk->group_leader)
1596 continue;
1597 if (g->flags & PF_KTHREAD)
1598 continue;
1599 p = g;
1600 do {
1601 if (p->mm) {
1602 if (unlikely(p->mm == mm)) {
1603 lock_task_sighand(p, &flags);
1604 nr += zap_process(p);
1605 unlock_task_sighand(p, &flags);
1606 }
1607 break;
1608 }
1609 } while_each_thread(g, p);
1610 }
1611 rcu_read_unlock();
1612 done:
1613 atomic_set(&core_state->nr_threads, nr);
1614 return nr;
1615 }
1616
coredump_wait(int exit_code,struct core_state * core_state)1617 static int coredump_wait(int exit_code, struct core_state *core_state)
1618 {
1619 struct task_struct *tsk = current;
1620 struct mm_struct *mm = tsk->mm;
1621 struct completion *vfork_done;
1622 int core_waiters;
1623
1624 init_completion(&core_state->startup);
1625 core_state->dumper.task = tsk;
1626 core_state->dumper.next = NULL;
1627 core_waiters = zap_threads(tsk, mm, core_state, exit_code);
1628 up_write(&mm->mmap_sem);
1629
1630 if (unlikely(core_waiters < 0))
1631 goto fail;
1632
1633 /*
1634 * Make sure nobody is waiting for us to release the VM,
1635 * otherwise we can deadlock when we wait on each other
1636 */
1637 vfork_done = tsk->vfork_done;
1638 if (vfork_done) {
1639 tsk->vfork_done = NULL;
1640 complete(vfork_done);
1641 }
1642
1643 if (core_waiters)
1644 wait_for_completion(&core_state->startup);
1645 fail:
1646 return core_waiters;
1647 }
1648
coredump_finish(struct mm_struct * mm)1649 static void coredump_finish(struct mm_struct *mm)
1650 {
1651 struct core_thread *curr, *next;
1652 struct task_struct *task;
1653
1654 next = mm->core_state->dumper.next;
1655 while ((curr = next) != NULL) {
1656 next = curr->next;
1657 task = curr->task;
1658 /*
1659 * see exit_mm(), curr->task must not see
1660 * ->task == NULL before we read ->next.
1661 */
1662 smp_mb();
1663 curr->task = NULL;
1664 wake_up_process(task);
1665 }
1666
1667 mm->core_state = NULL;
1668 }
1669
1670 /*
1671 * set_dumpable converts traditional three-value dumpable to two flags and
1672 * stores them into mm->flags. It modifies lower two bits of mm->flags, but
1673 * these bits are not changed atomically. So get_dumpable can observe the
1674 * intermediate state. To avoid doing unexpected behavior, get get_dumpable
1675 * return either old dumpable or new one by paying attention to the order of
1676 * modifying the bits.
1677 *
1678 * dumpable | mm->flags (binary)
1679 * old new | initial interim final
1680 * ---------+-----------------------
1681 * 0 1 | 00 01 01
1682 * 0 2 | 00 10(*) 11
1683 * 1 0 | 01 00 00
1684 * 1 2 | 01 11 11
1685 * 2 0 | 11 10(*) 00
1686 * 2 1 | 11 11 01
1687 *
1688 * (*) get_dumpable regards interim value of 10 as 11.
1689 */
set_dumpable(struct mm_struct * mm,int value)1690 void set_dumpable(struct mm_struct *mm, int value)
1691 {
1692 switch (value) {
1693 case 0:
1694 clear_bit(MMF_DUMPABLE, &mm->flags);
1695 smp_wmb();
1696 clear_bit(MMF_DUMP_SECURELY, &mm->flags);
1697 break;
1698 case 1:
1699 set_bit(MMF_DUMPABLE, &mm->flags);
1700 smp_wmb();
1701 clear_bit(MMF_DUMP_SECURELY, &mm->flags);
1702 break;
1703 case 2:
1704 set_bit(MMF_DUMP_SECURELY, &mm->flags);
1705 smp_wmb();
1706 set_bit(MMF_DUMPABLE, &mm->flags);
1707 break;
1708 }
1709 }
1710
get_dumpable(struct mm_struct * mm)1711 int get_dumpable(struct mm_struct *mm)
1712 {
1713 int ret;
1714
1715 ret = mm->flags & 0x3;
1716 return (ret >= 2) ? 2 : ret;
1717 }
1718
do_coredump(long signr,int exit_code,struct pt_regs * regs)1719 void do_coredump(long signr, int exit_code, struct pt_regs *regs)
1720 {
1721 struct core_state core_state;
1722 char corename[CORENAME_MAX_SIZE + 1];
1723 struct mm_struct *mm = current->mm;
1724 struct linux_binfmt * binfmt;
1725 struct inode * inode;
1726 struct file * file;
1727 const struct cred *old_cred;
1728 struct cred *cred;
1729 int retval = 0;
1730 int flag = 0;
1731 int ispipe = 0;
1732 unsigned long core_limit = current->signal->rlim[RLIMIT_CORE].rlim_cur;
1733 char **helper_argv = NULL;
1734 int helper_argc = 0;
1735 char *delimit;
1736
1737 audit_core_dumps(signr);
1738
1739 binfmt = current->binfmt;
1740 if (!binfmt || !binfmt->core_dump)
1741 goto fail;
1742
1743 cred = prepare_creds();
1744 if (!cred) {
1745 retval = -ENOMEM;
1746 goto fail;
1747 }
1748
1749 down_write(&mm->mmap_sem);
1750 /*
1751 * If another thread got here first, or we are not dumpable, bail out.
1752 */
1753 if (mm->core_state || !get_dumpable(mm)) {
1754 up_write(&mm->mmap_sem);
1755 put_cred(cred);
1756 goto fail;
1757 }
1758
1759 /*
1760 * We cannot trust fsuid as being the "true" uid of the
1761 * process nor do we know its entire history. We only know it
1762 * was tainted so we dump it as root in mode 2.
1763 */
1764 if (get_dumpable(mm) == 2) { /* Setuid core dump mode */
1765 flag = O_EXCL; /* Stop rewrite attacks */
1766 cred->fsuid = 0; /* Dump root private */
1767 }
1768
1769 retval = coredump_wait(exit_code, &core_state);
1770 if (retval < 0) {
1771 put_cred(cred);
1772 goto fail;
1773 }
1774
1775 old_cred = override_creds(cred);
1776
1777 /*
1778 * Clear any false indication of pending signals that might
1779 * be seen by the filesystem code called to write the core file.
1780 */
1781 clear_thread_flag(TIF_SIGPENDING);
1782
1783 /*
1784 * lock_kernel() because format_corename() is controlled by sysctl, which
1785 * uses lock_kernel()
1786 */
1787 lock_kernel();
1788 ispipe = format_corename(corename, signr);
1789 unlock_kernel();
1790 /*
1791 * Don't bother to check the RLIMIT_CORE value if core_pattern points
1792 * to a pipe. Since we're not writing directly to the filesystem
1793 * RLIMIT_CORE doesn't really apply, as no actual core file will be
1794 * created unless the pipe reader choses to write out the core file
1795 * at which point file size limits and permissions will be imposed
1796 * as it does with any other process
1797 */
1798 if ((!ispipe) && (core_limit < binfmt->min_coredump))
1799 goto fail_unlock;
1800
1801 if (ispipe) {
1802 helper_argv = argv_split(GFP_KERNEL, corename+1, &helper_argc);
1803 if (!helper_argv) {
1804 printk(KERN_WARNING "%s failed to allocate memory\n",
1805 __func__);
1806 goto fail_unlock;
1807 }
1808 /* Terminate the string before the first option */
1809 delimit = strchr(corename, ' ');
1810 if (delimit)
1811 *delimit = '\0';
1812 delimit = strrchr(helper_argv[0], '/');
1813 if (delimit)
1814 delimit++;
1815 else
1816 delimit = helper_argv[0];
1817 if (!strcmp(delimit, current->comm)) {
1818 printk(KERN_NOTICE "Recursive core dump detected, "
1819 "aborting\n");
1820 goto fail_unlock;
1821 }
1822
1823 core_limit = RLIM_INFINITY;
1824
1825 /* SIGPIPE can happen, but it's just never processed */
1826 if (call_usermodehelper_pipe(corename+1, helper_argv, NULL,
1827 &file)) {
1828 printk(KERN_INFO "Core dump to %s pipe failed\n",
1829 corename);
1830 goto fail_unlock;
1831 }
1832 } else
1833 file = filp_open(corename,
1834 O_CREAT | 2 | O_NOFOLLOW | O_LARGEFILE | flag,
1835 0600);
1836 if (IS_ERR(file))
1837 goto fail_unlock;
1838 inode = file->f_path.dentry->d_inode;
1839 if (inode->i_nlink > 1)
1840 goto close_fail; /* multiple links - don't dump */
1841 if (!ispipe && d_unhashed(file->f_path.dentry))
1842 goto close_fail;
1843
1844 /* AK: actually i see no reason to not allow this for named pipes etc.,
1845 but keep the previous behaviour for now. */
1846 if (!ispipe && !S_ISREG(inode->i_mode))
1847 goto close_fail;
1848 /*
1849 * Dont allow local users get cute and trick others to coredump
1850 * into their pre-created files:
1851 */
1852 if (inode->i_uid != current_fsuid())
1853 goto close_fail;
1854 if (!file->f_op)
1855 goto close_fail;
1856 if (!file->f_op->write)
1857 goto close_fail;
1858 if (!ispipe && do_truncate(file->f_path.dentry, 0, 0, file) != 0)
1859 goto close_fail;
1860
1861 retval = binfmt->core_dump(signr, regs, file, core_limit);
1862
1863 if (retval)
1864 current->signal->group_exit_code |= 0x80;
1865 close_fail:
1866 filp_close(file, NULL);
1867 fail_unlock:
1868 if (helper_argv)
1869 argv_free(helper_argv);
1870
1871 revert_creds(old_cred);
1872 put_cred(cred);
1873 coredump_finish(mm);
1874 fail:
1875 return;
1876 }
1877