Fix gcc 4.5.1 miscompiling drivers/char/i8k.c (again)
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / fs / exec.c
blob2fbb22c26f0e5ff9b1ce1dfed42c696f836a6824
1 /*
2 * linux/fs/exec.c
4 * Copyright (C) 1991, 1992 Linus Torvalds
5 */
7 /*
8 * #!-checking implemented by tytso.
9 */
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.
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.
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.
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/perf_event.h>
37 #include <linux/highmem.h>
38 #include <linux/spinlock.h>
39 #include <linux/key.h>
40 #include <linux/personality.h>
41 #include <linux/binfmts.h>
42 #include <linux/utsname.h>
43 #include <linux/pid_namespace.h>
44 #include <linux/module.h>
45 #include <linux/namei.h>
46 #include <linux/proc_fs.h>
47 #include <linux/mount.h>
48 #include <linux/security.h>
49 #include <linux/syscalls.h>
50 #include <linux/tsacct_kern.h>
51 #include <linux/cn_proc.h>
52 #include <linux/audit.h>
53 #include <linux/tracehook.h>
54 #include <linux/kmod.h>
55 #include <linux/fsnotify.h>
56 #include <linux/fs_struct.h>
57 #include <linux/pipe_fs_i.h>
59 #include <asm/uaccess.h>
60 #include <asm/mmu_context.h>
61 #include <asm/tlb.h>
62 #include "internal.h"
64 int core_uses_pid;
65 char core_pattern[CORENAME_MAX_SIZE] = "core";
66 unsigned int core_pipe_limit;
67 int suid_dumpable = 0;
69 /* The maximal length of core_pattern is also specified in sysctl.c */
71 static LIST_HEAD(formats);
72 static DEFINE_RWLOCK(binfmt_lock);
74 int __register_binfmt(struct linux_binfmt * fmt, int insert)
76 if (!fmt)
77 return -EINVAL;
78 write_lock(&binfmt_lock);
79 insert ? list_add(&fmt->lh, &formats) :
80 list_add_tail(&fmt->lh, &formats);
81 write_unlock(&binfmt_lock);
82 return 0;
85 EXPORT_SYMBOL(__register_binfmt);
87 void unregister_binfmt(struct linux_binfmt * fmt)
89 write_lock(&binfmt_lock);
90 list_del(&fmt->lh);
91 write_unlock(&binfmt_lock);
94 EXPORT_SYMBOL(unregister_binfmt);
96 static inline void put_binfmt(struct linux_binfmt * fmt)
98 module_put(fmt->module);
102 * Note that a shared library must be both readable and executable due to
103 * security reasons.
105 * Also note that we take the address to load from from the file itself.
107 SYSCALL_DEFINE1(uselib, const char __user *, library)
109 struct file *file;
110 char *tmp = getname(library);
111 int error = PTR_ERR(tmp);
113 if (IS_ERR(tmp))
114 goto out;
116 file = do_filp_open(AT_FDCWD, tmp,
117 O_LARGEFILE | O_RDONLY | FMODE_EXEC, 0,
118 MAY_READ | MAY_EXEC | MAY_OPEN);
119 putname(tmp);
120 error = PTR_ERR(file);
121 if (IS_ERR(file))
122 goto out;
124 error = -EINVAL;
125 if (!S_ISREG(file->f_path.dentry->d_inode->i_mode))
126 goto exit;
128 error = -EACCES;
129 if (file->f_path.mnt->mnt_flags & MNT_NOEXEC)
130 goto exit;
132 fsnotify_open(file->f_path.dentry);
134 error = -ENOEXEC;
135 if(file->f_op) {
136 struct linux_binfmt * fmt;
138 read_lock(&binfmt_lock);
139 list_for_each_entry(fmt, &formats, lh) {
140 if (!fmt->load_shlib)
141 continue;
142 if (!try_module_get(fmt->module))
143 continue;
144 read_unlock(&binfmt_lock);
145 error = fmt->load_shlib(file);
146 read_lock(&binfmt_lock);
147 put_binfmt(fmt);
148 if (error != -ENOEXEC)
149 break;
151 read_unlock(&binfmt_lock);
153 exit:
154 fput(file);
155 out:
156 return error;
159 #ifdef CONFIG_MMU
161 void acct_arg_size(struct linux_binprm *bprm, unsigned long pages)
163 struct mm_struct *mm = current->mm;
164 long diff = (long)(pages - bprm->vma_pages);
166 if (!mm || !diff)
167 return;
169 bprm->vma_pages = pages;
171 down_write(&mm->mmap_sem);
172 mm->total_vm += diff;
173 up_write(&mm->mmap_sem);
176 struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
177 int write)
179 struct page *page;
180 int ret;
182 #ifdef CONFIG_STACK_GROWSUP
183 if (write) {
184 ret = expand_stack_downwards(bprm->vma, pos);
185 if (ret < 0)
186 return NULL;
188 #endif
189 ret = get_user_pages(current, bprm->mm, pos,
190 1, write, 1, &page, NULL);
191 if (ret <= 0)
192 return NULL;
194 if (write) {
195 unsigned long size = bprm->vma->vm_end - bprm->vma->vm_start;
196 struct rlimit *rlim;
198 acct_arg_size(bprm, size / PAGE_SIZE);
201 * We've historically supported up to 32 pages (ARG_MAX)
202 * of argument strings even with small stacks
204 if (size <= ARG_MAX)
205 return page;
208 * Limit to 1/4-th the stack size for the argv+env strings.
209 * This ensures that:
210 * - the remaining binfmt code will not run out of stack space,
211 * - the program will have a reasonable amount of stack left
212 * to work from.
214 rlim = current->signal->rlim;
215 if (size > rlim[RLIMIT_STACK].rlim_cur / 4) {
216 put_page(page);
217 return NULL;
221 return page;
224 static void put_arg_page(struct page *page)
226 put_page(page);
229 static void free_arg_page(struct linux_binprm *bprm, int i)
233 static void free_arg_pages(struct linux_binprm *bprm)
237 static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
238 struct page *page)
240 flush_cache_page(bprm->vma, pos, page_to_pfn(page));
243 static int __bprm_mm_init(struct linux_binprm *bprm)
245 int err;
246 struct vm_area_struct *vma = NULL;
247 struct mm_struct *mm = bprm->mm;
249 bprm->vma = vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
250 if (!vma)
251 return -ENOMEM;
253 down_write(&mm->mmap_sem);
254 vma->vm_mm = mm;
257 * Place the stack at the largest stack address the architecture
258 * supports. Later, we'll move this to an appropriate place. We don't
259 * use STACK_TOP because that can depend on attributes which aren't
260 * configured yet.
262 vma->vm_end = STACK_TOP_MAX;
263 vma->vm_start = vma->vm_end - PAGE_SIZE;
264 vma->vm_flags = VM_STACK_FLAGS;
265 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
267 err = security_file_mmap(NULL, 0, 0, 0, vma->vm_start, 1);
268 if (err)
269 goto err;
271 err = insert_vm_struct(mm, vma);
272 if (err)
273 goto err;
275 mm->stack_vm = mm->total_vm = 1;
276 up_write(&mm->mmap_sem);
277 bprm->p = vma->vm_end - sizeof(void *);
278 return 0;
279 err:
280 up_write(&mm->mmap_sem);
281 bprm->vma = NULL;
282 kmem_cache_free(vm_area_cachep, vma);
283 return err;
286 static bool valid_arg_len(struct linux_binprm *bprm, long len)
288 return len <= MAX_ARG_STRLEN;
291 #else
293 void acct_arg_size(struct linux_binprm *bprm, unsigned long pages)
297 struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
298 int write)
300 struct page *page;
302 page = bprm->page[pos / PAGE_SIZE];
303 if (!page && write) {
304 page = alloc_page(GFP_HIGHUSER|__GFP_ZERO);
305 if (!page)
306 return NULL;
307 bprm->page[pos / PAGE_SIZE] = page;
310 return page;
313 static void put_arg_page(struct page *page)
317 static void free_arg_page(struct linux_binprm *bprm, int i)
319 if (bprm->page[i]) {
320 __free_page(bprm->page[i]);
321 bprm->page[i] = NULL;
325 static void free_arg_pages(struct linux_binprm *bprm)
327 int i;
329 for (i = 0; i < MAX_ARG_PAGES; i++)
330 free_arg_page(bprm, i);
333 static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
334 struct page *page)
338 static int __bprm_mm_init(struct linux_binprm *bprm)
340 bprm->p = PAGE_SIZE * MAX_ARG_PAGES - sizeof(void *);
341 return 0;
344 static bool valid_arg_len(struct linux_binprm *bprm, long len)
346 return len <= bprm->p;
349 #endif /* CONFIG_MMU */
352 * Create a new mm_struct and populate it with a temporary stack
353 * vm_area_struct. We don't have enough context at this point to set the stack
354 * flags, permissions, and offset, so we use temporary values. We'll update
355 * them later in setup_arg_pages().
357 int bprm_mm_init(struct linux_binprm *bprm)
359 int err;
360 struct mm_struct *mm = NULL;
362 bprm->mm = mm = mm_alloc();
363 err = -ENOMEM;
364 if (!mm)
365 goto err;
367 err = init_new_context(current, mm);
368 if (err)
369 goto err;
371 err = __bprm_mm_init(bprm);
372 if (err)
373 goto err;
375 return 0;
377 err:
378 if (mm) {
379 bprm->mm = NULL;
380 mmdrop(mm);
383 return err;
387 * count() counts the number of strings in array ARGV.
389 static int count(char __user * __user * argv, int max)
391 int i = 0;
393 if (argv != NULL) {
394 for (;;) {
395 char __user * p;
397 if (get_user(p, argv))
398 return -EFAULT;
399 if (!p)
400 break;
401 argv++;
402 if (i++ >= max)
403 return -E2BIG;
405 if (fatal_signal_pending(current))
406 return -ERESTARTNOHAND;
407 cond_resched();
410 return i;
414 * 'copy_strings()' copies argument/environment strings from the old
415 * processes's memory to the new process's stack. The call to get_user_pages()
416 * ensures the destination page is created and not swapped out.
418 static int copy_strings(int argc, char __user * __user * argv,
419 struct linux_binprm *bprm)
421 struct page *kmapped_page = NULL;
422 char *kaddr = NULL;
423 unsigned long kpos = 0;
424 int ret;
426 while (argc-- > 0) {
427 char __user *str;
428 int len;
429 unsigned long pos;
431 if (get_user(str, argv+argc) ||
432 !(len = strnlen_user(str, MAX_ARG_STRLEN))) {
433 ret = -EFAULT;
434 goto out;
437 if (!valid_arg_len(bprm, len)) {
438 ret = -E2BIG;
439 goto out;
442 /* We're going to work our way backwords. */
443 pos = bprm->p;
444 str += len;
445 bprm->p -= len;
447 while (len > 0) {
448 int offset, bytes_to_copy;
450 if (fatal_signal_pending(current)) {
451 ret = -ERESTARTNOHAND;
452 goto out;
454 cond_resched();
456 offset = pos % PAGE_SIZE;
457 if (offset == 0)
458 offset = PAGE_SIZE;
460 bytes_to_copy = offset;
461 if (bytes_to_copy > len)
462 bytes_to_copy = len;
464 offset -= bytes_to_copy;
465 pos -= bytes_to_copy;
466 str -= bytes_to_copy;
467 len -= bytes_to_copy;
469 if (!kmapped_page || kpos != (pos & PAGE_MASK)) {
470 struct page *page;
472 page = get_arg_page(bprm, pos, 1);
473 if (!page) {
474 ret = -E2BIG;
475 goto out;
478 if (kmapped_page) {
479 flush_kernel_dcache_page(kmapped_page);
480 kunmap(kmapped_page);
481 put_arg_page(kmapped_page);
483 kmapped_page = page;
484 kaddr = kmap(kmapped_page);
485 kpos = pos & PAGE_MASK;
486 flush_arg_page(bprm, kpos, kmapped_page);
488 if (copy_from_user(kaddr+offset, str, bytes_to_copy)) {
489 ret = -EFAULT;
490 goto out;
494 ret = 0;
495 out:
496 if (kmapped_page) {
497 flush_kernel_dcache_page(kmapped_page);
498 kunmap(kmapped_page);
499 put_arg_page(kmapped_page);
501 return ret;
505 * Like copy_strings, but get argv and its values from kernel memory.
507 int copy_strings_kernel(int argc,char ** argv, struct linux_binprm *bprm)
509 int r;
510 mm_segment_t oldfs = get_fs();
511 set_fs(KERNEL_DS);
512 r = copy_strings(argc, (char __user * __user *)argv, bprm);
513 set_fs(oldfs);
514 return r;
516 EXPORT_SYMBOL(copy_strings_kernel);
518 #ifdef CONFIG_MMU
521 * During bprm_mm_init(), we create a temporary stack at STACK_TOP_MAX. Once
522 * the binfmt code determines where the new stack should reside, we shift it to
523 * its final location. The process proceeds as follows:
525 * 1) Use shift to calculate the new vma endpoints.
526 * 2) Extend vma to cover both the old and new ranges. This ensures the
527 * arguments passed to subsequent functions are consistent.
528 * 3) Move vma's page tables to the new range.
529 * 4) Free up any cleared pgd range.
530 * 5) Shrink the vma to cover only the new range.
532 static int shift_arg_pages(struct vm_area_struct *vma, unsigned long shift)
534 struct mm_struct *mm = vma->vm_mm;
535 unsigned long old_start = vma->vm_start;
536 unsigned long old_end = vma->vm_end;
537 unsigned long length = old_end - old_start;
538 unsigned long new_start = old_start - shift;
539 unsigned long new_end = old_end - shift;
540 struct mmu_gather *tlb;
542 BUG_ON(new_start > new_end);
545 * ensure there are no vmas between where we want to go
546 * and where we are
548 if (vma != find_vma(mm, new_start))
549 return -EFAULT;
552 * cover the whole range: [new_start, old_end)
554 vma_adjust(vma, new_start, old_end, vma->vm_pgoff, NULL);
557 * move the page tables downwards, on failure we rely on
558 * process cleanup to remove whatever mess we made.
560 if (length != move_page_tables(vma, old_start,
561 vma, new_start, length))
562 return -ENOMEM;
564 lru_add_drain();
565 tlb = tlb_gather_mmu(mm, 0);
566 if (new_end > old_start) {
568 * when the old and new regions overlap clear from new_end.
570 free_pgd_range(tlb, new_end, old_end, new_end,
571 vma->vm_next ? vma->vm_next->vm_start : 0);
572 } else {
574 * otherwise, clean from old_start; this is done to not touch
575 * the address space in [new_end, old_start) some architectures
576 * have constraints on va-space that make this illegal (IA64) -
577 * for the others its just a little faster.
579 free_pgd_range(tlb, old_start, old_end, new_end,
580 vma->vm_next ? vma->vm_next->vm_start : 0);
582 tlb_finish_mmu(tlb, new_end, old_end);
585 * shrink the vma to just the new range.
587 vma_adjust(vma, new_start, new_end, vma->vm_pgoff, NULL);
589 return 0;
592 #define EXTRA_STACK_VM_PAGES 20 /* random */
595 * Finalizes the stack vm_area_struct. The flags and permissions are updated,
596 * the stack is optionally relocated, and some extra space is added.
598 int setup_arg_pages(struct linux_binprm *bprm,
599 unsigned long stack_top,
600 int executable_stack)
602 unsigned long ret;
603 unsigned long stack_shift;
604 struct mm_struct *mm = current->mm;
605 struct vm_area_struct *vma = bprm->vma;
606 struct vm_area_struct *prev = NULL;
607 unsigned long vm_flags;
608 unsigned long stack_base;
609 unsigned long stack_size;
610 unsigned long stack_expand;
611 unsigned long rlim_stack;
613 #ifdef CONFIG_STACK_GROWSUP
614 /* Limit stack size to 1GB */
615 stack_base = current->signal->rlim[RLIMIT_STACK].rlim_max;
616 if (stack_base > (1 << 30))
617 stack_base = 1 << 30;
619 /* Make sure we didn't let the argument array grow too large. */
620 if (vma->vm_end - vma->vm_start > stack_base)
621 return -ENOMEM;
623 stack_base = PAGE_ALIGN(stack_top - stack_base);
625 stack_shift = vma->vm_start - stack_base;
626 mm->arg_start = bprm->p - stack_shift;
627 bprm->p = vma->vm_end - stack_shift;
628 #else
629 stack_top = arch_align_stack(stack_top);
630 stack_top = PAGE_ALIGN(stack_top);
632 if (unlikely(stack_top < mmap_min_addr) ||
633 unlikely(vma->vm_end - vma->vm_start >= stack_top - mmap_min_addr))
634 return -ENOMEM;
636 stack_shift = vma->vm_end - stack_top;
638 bprm->p -= stack_shift;
639 mm->arg_start = bprm->p;
640 #endif
642 if (bprm->loader)
643 bprm->loader -= stack_shift;
644 bprm->exec -= stack_shift;
646 down_write(&mm->mmap_sem);
647 vm_flags = VM_STACK_FLAGS;
650 * Adjust stack execute permissions; explicitly enable for
651 * EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X and leave alone
652 * (arch default) otherwise.
654 if (unlikely(executable_stack == EXSTACK_ENABLE_X))
655 vm_flags |= VM_EXEC;
656 else if (executable_stack == EXSTACK_DISABLE_X)
657 vm_flags &= ~VM_EXEC;
658 vm_flags |= mm->def_flags;
660 ret = mprotect_fixup(vma, &prev, vma->vm_start, vma->vm_end,
661 vm_flags);
662 if (ret)
663 goto out_unlock;
664 BUG_ON(prev != vma);
666 /* Move stack pages down in memory. */
667 if (stack_shift) {
668 ret = shift_arg_pages(vma, stack_shift);
669 if (ret)
670 goto out_unlock;
673 stack_expand = EXTRA_STACK_VM_PAGES * PAGE_SIZE;
674 stack_size = vma->vm_end - vma->vm_start;
676 * Align this down to a page boundary as expand_stack
677 * will align it up.
679 rlim_stack = rlimit(RLIMIT_STACK) & PAGE_MASK;
680 #ifdef CONFIG_STACK_GROWSUP
681 if (stack_size + stack_expand > rlim_stack)
682 stack_base = vma->vm_start + rlim_stack;
683 else
684 stack_base = vma->vm_end + stack_expand;
685 #else
686 if (stack_size + stack_expand > rlim_stack)
687 stack_base = vma->vm_end - rlim_stack;
688 else
689 stack_base = vma->vm_start - stack_expand;
690 #endif
691 ret = expand_stack(vma, stack_base);
692 if (ret)
693 ret = -EFAULT;
695 out_unlock:
696 up_write(&mm->mmap_sem);
697 return ret;
699 EXPORT_SYMBOL(setup_arg_pages);
701 #endif /* CONFIG_MMU */
703 struct file *open_exec(const char *name)
705 struct file *file;
706 int err;
708 file = do_filp_open(AT_FDCWD, name,
709 O_LARGEFILE | O_RDONLY | FMODE_EXEC, 0,
710 MAY_EXEC | MAY_OPEN);
711 if (IS_ERR(file))
712 goto out;
714 err = -EACCES;
715 if (!S_ISREG(file->f_path.dentry->d_inode->i_mode))
716 goto exit;
718 if (file->f_path.mnt->mnt_flags & MNT_NOEXEC)
719 goto exit;
721 fsnotify_open(file->f_path.dentry);
723 err = deny_write_access(file);
724 if (err)
725 goto exit;
727 out:
728 return file;
730 exit:
731 fput(file);
732 return ERR_PTR(err);
734 EXPORT_SYMBOL(open_exec);
736 int kernel_read(struct file *file, loff_t offset,
737 char *addr, unsigned long count)
739 mm_segment_t old_fs;
740 loff_t pos = offset;
741 int result;
743 old_fs = get_fs();
744 set_fs(get_ds());
745 /* The cast to a user pointer is valid due to the set_fs() */
746 result = vfs_read(file, (void __user *)addr, count, &pos);
747 set_fs(old_fs);
748 return result;
751 EXPORT_SYMBOL(kernel_read);
753 static int exec_mmap(struct mm_struct *mm)
755 struct task_struct *tsk;
756 struct mm_struct * old_mm, *active_mm;
758 /* Notify parent that we're no longer interested in the old VM */
759 tsk = current;
760 old_mm = current->mm;
761 mm_release(tsk, old_mm);
763 if (old_mm) {
765 * Make sure that if there is a core dump in progress
766 * for the old mm, we get out and die instead of going
767 * through with the exec. We must hold mmap_sem around
768 * checking core_state and changing tsk->mm.
770 down_read(&old_mm->mmap_sem);
771 if (unlikely(old_mm->core_state)) {
772 up_read(&old_mm->mmap_sem);
773 return -EINTR;
776 task_lock(tsk);
777 active_mm = tsk->active_mm;
778 tsk->mm = mm;
779 tsk->active_mm = mm;
780 activate_mm(active_mm, mm);
781 task_unlock(tsk);
782 arch_pick_mmap_layout(mm);
783 if (old_mm) {
784 up_read(&old_mm->mmap_sem);
785 BUG_ON(active_mm != old_mm);
786 mm_update_next_owner(old_mm);
787 mmput(old_mm);
788 return 0;
790 mmdrop(active_mm);
791 return 0;
795 * This function makes sure the current process has its own signal table,
796 * so that flush_signal_handlers can later reset the handlers without
797 * disturbing other processes. (Other processes might share the signal
798 * table via the CLONE_SIGHAND option to clone().)
800 static int de_thread(struct task_struct *tsk)
802 struct signal_struct *sig = tsk->signal;
803 struct sighand_struct *oldsighand = tsk->sighand;
804 spinlock_t *lock = &oldsighand->siglock;
805 int count;
807 if (thread_group_empty(tsk))
808 goto no_thread_group;
811 * Kill all other threads in the thread group.
813 spin_lock_irq(lock);
814 if (signal_group_exit(sig)) {
816 * Another group action in progress, just
817 * return so that the signal is processed.
819 spin_unlock_irq(lock);
820 return -EAGAIN;
822 sig->group_exit_task = tsk;
823 zap_other_threads(tsk);
825 /* Account for the thread group leader hanging around: */
826 count = thread_group_leader(tsk) ? 1 : 2;
827 sig->notify_count = count;
828 while (atomic_read(&sig->count) > count) {
829 __set_current_state(TASK_UNINTERRUPTIBLE);
830 spin_unlock_irq(lock);
831 schedule();
832 spin_lock_irq(lock);
834 spin_unlock_irq(lock);
837 * At this point all other threads have exited, all we have to
838 * do is to wait for the thread group leader to become inactive,
839 * and to assume its PID:
841 if (!thread_group_leader(tsk)) {
842 struct task_struct *leader = tsk->group_leader;
844 sig->notify_count = -1; /* for exit_notify() */
845 for (;;) {
846 write_lock_irq(&tasklist_lock);
847 if (likely(leader->exit_state))
848 break;
849 __set_current_state(TASK_UNINTERRUPTIBLE);
850 write_unlock_irq(&tasklist_lock);
851 schedule();
855 * The only record we have of the real-time age of a
856 * process, regardless of execs it's done, is start_time.
857 * All the past CPU time is accumulated in signal_struct
858 * from sister threads now dead. But in this non-leader
859 * exec, nothing survives from the original leader thread,
860 * whose birth marks the true age of this process now.
861 * When we take on its identity by switching to its PID, we
862 * also take its birthdate (always earlier than our own).
864 tsk->start_time = leader->start_time;
866 BUG_ON(!same_thread_group(leader, tsk));
867 BUG_ON(has_group_leader_pid(tsk));
869 * An exec() starts a new thread group with the
870 * TGID of the previous thread group. Rehash the
871 * two threads with a switched PID, and release
872 * the former thread group leader:
875 /* Become a process group leader with the old leader's pid.
876 * The old leader becomes a thread of the this thread group.
877 * Note: The old leader also uses this pid until release_task
878 * is called. Odd but simple and correct.
880 detach_pid(tsk, PIDTYPE_PID);
881 tsk->pid = leader->pid;
882 attach_pid(tsk, PIDTYPE_PID, task_pid(leader));
883 transfer_pid(leader, tsk, PIDTYPE_PGID);
884 transfer_pid(leader, tsk, PIDTYPE_SID);
886 list_replace_rcu(&leader->tasks, &tsk->tasks);
887 list_replace_init(&leader->sibling, &tsk->sibling);
889 tsk->group_leader = tsk;
890 leader->group_leader = tsk;
892 tsk->exit_signal = SIGCHLD;
894 BUG_ON(leader->exit_state != EXIT_ZOMBIE);
895 leader->exit_state = EXIT_DEAD;
896 write_unlock_irq(&tasklist_lock);
898 release_task(leader);
901 sig->group_exit_task = NULL;
902 sig->notify_count = 0;
904 no_thread_group:
905 if (current->mm)
906 setmax_mm_hiwater_rss(&sig->maxrss, current->mm);
908 exit_itimers(sig);
909 flush_itimer_signals();
911 if (atomic_read(&oldsighand->count) != 1) {
912 struct sighand_struct *newsighand;
914 * This ->sighand is shared with the CLONE_SIGHAND
915 * but not CLONE_THREAD task, switch to the new one.
917 newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
918 if (!newsighand)
919 return -ENOMEM;
921 atomic_set(&newsighand->count, 1);
922 memcpy(newsighand->action, oldsighand->action,
923 sizeof(newsighand->action));
925 write_lock_irq(&tasklist_lock);
926 spin_lock(&oldsighand->siglock);
927 rcu_assign_pointer(tsk->sighand, newsighand);
928 spin_unlock(&oldsighand->siglock);
929 write_unlock_irq(&tasklist_lock);
931 __cleanup_sighand(oldsighand);
934 BUG_ON(!thread_group_leader(tsk));
935 return 0;
939 * These functions flushes out all traces of the currently running executable
940 * so that a new one can be started
942 static void flush_old_files(struct files_struct * files)
944 long j = -1;
945 struct fdtable *fdt;
947 spin_lock(&files->file_lock);
948 for (;;) {
949 unsigned long set, i;
951 j++;
952 i = j * __NFDBITS;
953 fdt = files_fdtable(files);
954 if (i >= fdt->max_fds)
955 break;
956 set = fdt->close_on_exec->fds_bits[j];
957 if (!set)
958 continue;
959 fdt->close_on_exec->fds_bits[j] = 0;
960 spin_unlock(&files->file_lock);
961 for ( ; set ; i++,set >>= 1) {
962 if (set & 1) {
963 sys_close(i);
966 spin_lock(&files->file_lock);
969 spin_unlock(&files->file_lock);
972 char *get_task_comm(char *buf, struct task_struct *tsk)
974 /* buf must be at least sizeof(tsk->comm) in size */
975 task_lock(tsk);
976 strncpy(buf, tsk->comm, sizeof(tsk->comm));
977 task_unlock(tsk);
978 return buf;
981 void set_task_comm(struct task_struct *tsk, char *buf)
983 task_lock(tsk);
986 * Threads may access current->comm without holding
987 * the task lock, so write the string carefully.
988 * Readers without a lock may see incomplete new
989 * names but are safe from non-terminating string reads.
991 memset(tsk->comm, 0, TASK_COMM_LEN);
992 wmb();
993 strlcpy(tsk->comm, buf, sizeof(tsk->comm));
994 task_unlock(tsk);
995 perf_event_comm(tsk);
998 int flush_old_exec(struct linux_binprm * bprm)
1000 int retval;
1003 * Make sure we have a private signal table and that
1004 * we are unassociated from the previous thread group.
1006 retval = de_thread(current);
1007 if (retval)
1008 goto out;
1010 set_mm_exe_file(bprm->mm, bprm->file);
1013 * Release all of the old mmap stuff
1015 acct_arg_size(bprm, 0);
1016 retval = exec_mmap(bprm->mm);
1017 if (retval)
1018 goto out;
1020 bprm->mm = NULL; /* We're using it now */
1022 current->flags &= ~PF_RANDOMIZE;
1023 flush_thread();
1024 current->personality &= ~bprm->per_clear;
1026 return 0;
1028 out:
1029 return retval;
1031 EXPORT_SYMBOL(flush_old_exec);
1033 void setup_new_exec(struct linux_binprm * bprm)
1035 int i, ch;
1036 char * name;
1037 char tcomm[sizeof(current->comm)];
1039 arch_pick_mmap_layout(current->mm);
1041 /* This is the point of no return */
1042 current->sas_ss_sp = current->sas_ss_size = 0;
1044 if (current_euid() == current_uid() && current_egid() == current_gid())
1045 set_dumpable(current->mm, 1);
1046 else
1047 set_dumpable(current->mm, suid_dumpable);
1049 name = bprm->filename;
1051 /* Copies the binary name from after last slash */
1052 for (i=0; (ch = *(name++)) != '\0';) {
1053 if (ch == '/')
1054 i = 0; /* overwrite what we wrote */
1055 else
1056 if (i < (sizeof(tcomm) - 1))
1057 tcomm[i++] = ch;
1059 tcomm[i] = '\0';
1060 set_task_comm(current, tcomm);
1062 /* Set the new mm task size. We have to do that late because it may
1063 * depend on TIF_32BIT which is only updated in flush_thread() on
1064 * some architectures like powerpc
1066 current->mm->task_size = TASK_SIZE;
1068 /* install the new credentials */
1069 if (bprm->cred->uid != current_euid() ||
1070 bprm->cred->gid != current_egid()) {
1071 current->pdeath_signal = 0;
1072 } else if (file_permission(bprm->file, MAY_READ) ||
1073 bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP) {
1074 set_dumpable(current->mm, suid_dumpable);
1078 * Flush performance counters when crossing a
1079 * security domain:
1081 if (!get_dumpable(current->mm))
1082 perf_event_exit_task(current);
1084 /* An exec changes our domain. We are no longer part of the thread
1085 group */
1087 current->self_exec_id++;
1089 flush_signal_handlers(current, 0);
1090 flush_old_files(current->files);
1092 EXPORT_SYMBOL(setup_new_exec);
1095 * Prepare credentials and lock ->cred_guard_mutex.
1096 * install_exec_creds() commits the new creds and drops the lock.
1097 * Or, if exec fails before, free_bprm() should release ->cred and
1098 * and unlock.
1100 int prepare_bprm_creds(struct linux_binprm *bprm)
1102 if (mutex_lock_interruptible(&current->cred_guard_mutex))
1103 return -ERESTARTNOINTR;
1105 bprm->cred = prepare_exec_creds();
1106 if (likely(bprm->cred))
1107 return 0;
1109 mutex_unlock(&current->cred_guard_mutex);
1110 return -ENOMEM;
1113 void free_bprm(struct linux_binprm *bprm)
1115 free_arg_pages(bprm);
1116 if (bprm->cred) {
1117 mutex_unlock(&current->cred_guard_mutex);
1118 abort_creds(bprm->cred);
1120 kfree(bprm);
1124 * install the new credentials for this executable
1126 void install_exec_creds(struct linux_binprm *bprm)
1128 security_bprm_committing_creds(bprm);
1130 commit_creds(bprm->cred);
1131 bprm->cred = NULL;
1133 * cred_guard_mutex must be held at least to this point to prevent
1134 * ptrace_attach() from altering our determination of the task's
1135 * credentials; any time after this it may be unlocked.
1137 security_bprm_committed_creds(bprm);
1138 mutex_unlock(&current->cred_guard_mutex);
1140 EXPORT_SYMBOL(install_exec_creds);
1143 * determine how safe it is to execute the proposed program
1144 * - the caller must hold current->cred_guard_mutex to protect against
1145 * PTRACE_ATTACH
1147 int check_unsafe_exec(struct linux_binprm *bprm)
1149 struct task_struct *p = current, *t;
1150 unsigned n_fs;
1151 int res = 0;
1153 bprm->unsafe = tracehook_unsafe_exec(p);
1155 n_fs = 1;
1156 write_lock(&p->fs->lock);
1157 rcu_read_lock();
1158 for (t = next_thread(p); t != p; t = next_thread(t)) {
1159 if (t->fs == p->fs)
1160 n_fs++;
1162 rcu_read_unlock();
1164 if (p->fs->users > n_fs) {
1165 bprm->unsafe |= LSM_UNSAFE_SHARE;
1166 } else {
1167 res = -EAGAIN;
1168 if (!p->fs->in_exec) {
1169 p->fs->in_exec = 1;
1170 res = 1;
1173 write_unlock(&p->fs->lock);
1175 return res;
1179 * Fill the binprm structure from the inode.
1180 * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
1182 * This may be called multiple times for binary chains (scripts for example).
1184 int prepare_binprm(struct linux_binprm *bprm)
1186 umode_t mode;
1187 struct inode * inode = bprm->file->f_path.dentry->d_inode;
1188 int retval;
1190 mode = inode->i_mode;
1191 if (bprm->file->f_op == NULL)
1192 return -EACCES;
1194 /* clear any previous set[ug]id data from a previous binary */
1195 bprm->cred->euid = current_euid();
1196 bprm->cred->egid = current_egid();
1198 if (!(bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID)) {
1199 /* Set-uid? */
1200 if (mode & S_ISUID) {
1201 bprm->per_clear |= PER_CLEAR_ON_SETID;
1202 bprm->cred->euid = inode->i_uid;
1205 /* Set-gid? */
1207 * If setgid is set but no group execute bit then this
1208 * is a candidate for mandatory locking, not a setgid
1209 * executable.
1211 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
1212 bprm->per_clear |= PER_CLEAR_ON_SETID;
1213 bprm->cred->egid = inode->i_gid;
1217 /* fill in binprm security blob */
1218 retval = security_bprm_set_creds(bprm);
1219 if (retval)
1220 return retval;
1221 bprm->cred_prepared = 1;
1223 memset(bprm->buf, 0, BINPRM_BUF_SIZE);
1224 return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
1227 EXPORT_SYMBOL(prepare_binprm);
1230 * Arguments are '\0' separated strings found at the location bprm->p
1231 * points to; chop off the first by relocating brpm->p to right after
1232 * the first '\0' encountered.
1234 int remove_arg_zero(struct linux_binprm *bprm)
1236 int ret = 0;
1237 unsigned long offset;
1238 char *kaddr;
1239 struct page *page;
1241 if (!bprm->argc)
1242 return 0;
1244 do {
1245 offset = bprm->p & ~PAGE_MASK;
1246 page = get_arg_page(bprm, bprm->p, 0);
1247 if (!page) {
1248 ret = -EFAULT;
1249 goto out;
1251 kaddr = kmap_atomic(page, KM_USER0);
1253 for (; offset < PAGE_SIZE && kaddr[offset];
1254 offset++, bprm->p++)
1257 kunmap_atomic(kaddr, KM_USER0);
1258 put_arg_page(page);
1260 if (offset == PAGE_SIZE)
1261 free_arg_page(bprm, (bprm->p >> PAGE_SHIFT) - 1);
1262 } while (offset == PAGE_SIZE);
1264 bprm->p++;
1265 bprm->argc--;
1266 ret = 0;
1268 out:
1269 return ret;
1271 EXPORT_SYMBOL(remove_arg_zero);
1274 * cycle the list of binary formats handler, until one recognizes the image
1276 int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs)
1278 unsigned int depth = bprm->recursion_depth;
1279 int try,retval;
1280 struct linux_binfmt *fmt;
1282 retval = security_bprm_check(bprm);
1283 if (retval)
1284 return retval;
1286 /* kernel module loader fixup */
1287 /* so we don't try to load run modprobe in kernel space. */
1288 set_fs(USER_DS);
1290 retval = audit_bprm(bprm);
1291 if (retval)
1292 return retval;
1294 retval = -ENOENT;
1295 for (try=0; try<2; try++) {
1296 read_lock(&binfmt_lock);
1297 list_for_each_entry(fmt, &formats, lh) {
1298 int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
1299 if (!fn)
1300 continue;
1301 if (!try_module_get(fmt->module))
1302 continue;
1303 read_unlock(&binfmt_lock);
1304 retval = fn(bprm, regs);
1306 * Restore the depth counter to its starting value
1307 * in this call, so we don't have to rely on every
1308 * load_binary function to restore it on return.
1310 bprm->recursion_depth = depth;
1311 if (retval >= 0) {
1312 if (depth == 0)
1313 tracehook_report_exec(fmt, bprm, regs);
1314 put_binfmt(fmt);
1315 allow_write_access(bprm->file);
1316 if (bprm->file)
1317 fput(bprm->file);
1318 bprm->file = NULL;
1319 current->did_exec = 1;
1320 proc_exec_connector(current);
1321 return retval;
1323 read_lock(&binfmt_lock);
1324 put_binfmt(fmt);
1325 if (retval != -ENOEXEC || bprm->mm == NULL)
1326 break;
1327 if (!bprm->file) {
1328 read_unlock(&binfmt_lock);
1329 return retval;
1332 read_unlock(&binfmt_lock);
1333 if (retval != -ENOEXEC || bprm->mm == NULL) {
1334 break;
1335 #ifdef CONFIG_MODULES
1336 } else {
1337 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
1338 if (printable(bprm->buf[0]) &&
1339 printable(bprm->buf[1]) &&
1340 printable(bprm->buf[2]) &&
1341 printable(bprm->buf[3]))
1342 break; /* -ENOEXEC */
1343 request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
1344 #endif
1347 return retval;
1350 EXPORT_SYMBOL(search_binary_handler);
1353 * sys_execve() executes a new program.
1355 int do_execve(char * filename,
1356 char __user *__user *argv,
1357 char __user *__user *envp,
1358 struct pt_regs * regs)
1360 struct linux_binprm *bprm;
1361 struct file *file;
1362 struct files_struct *displaced;
1363 bool clear_in_exec;
1364 int retval;
1366 retval = unshare_files(&displaced);
1367 if (retval)
1368 goto out_ret;
1370 retval = -ENOMEM;
1371 bprm = kzalloc(sizeof(*bprm), GFP_KERNEL);
1372 if (!bprm)
1373 goto out_files;
1375 retval = prepare_bprm_creds(bprm);
1376 if (retval)
1377 goto out_free;
1379 retval = check_unsafe_exec(bprm);
1380 if (retval < 0)
1381 goto out_free;
1382 clear_in_exec = retval;
1383 current->in_execve = 1;
1385 file = open_exec(filename);
1386 retval = PTR_ERR(file);
1387 if (IS_ERR(file))
1388 goto out_unmark;
1390 sched_exec();
1392 bprm->file = file;
1393 bprm->filename = filename;
1394 bprm->interp = filename;
1396 retval = bprm_mm_init(bprm);
1397 if (retval)
1398 goto out_file;
1400 bprm->argc = count(argv, MAX_ARG_STRINGS);
1401 if ((retval = bprm->argc) < 0)
1402 goto out;
1404 bprm->envc = count(envp, MAX_ARG_STRINGS);
1405 if ((retval = bprm->envc) < 0)
1406 goto out;
1408 retval = prepare_binprm(bprm);
1409 if (retval < 0)
1410 goto out;
1412 retval = copy_strings_kernel(1, &bprm->filename, bprm);
1413 if (retval < 0)
1414 goto out;
1416 bprm->exec = bprm->p;
1417 retval = copy_strings(bprm->envc, envp, bprm);
1418 if (retval < 0)
1419 goto out;
1421 retval = copy_strings(bprm->argc, argv, bprm);
1422 if (retval < 0)
1423 goto out;
1425 current->flags &= ~PF_KTHREAD;
1426 retval = search_binary_handler(bprm,regs);
1427 if (retval < 0)
1428 goto out;
1430 /* execve succeeded */
1431 current->fs->in_exec = 0;
1432 current->in_execve = 0;
1433 acct_update_integrals(current);
1434 free_bprm(bprm);
1435 if (displaced)
1436 put_files_struct(displaced);
1437 return retval;
1439 out:
1440 if (bprm->mm) {
1441 acct_arg_size(bprm, 0);
1442 mmput(bprm->mm);
1445 out_file:
1446 if (bprm->file) {
1447 allow_write_access(bprm->file);
1448 fput(bprm->file);
1451 out_unmark:
1452 if (clear_in_exec)
1453 current->fs->in_exec = 0;
1454 current->in_execve = 0;
1456 out_free:
1457 free_bprm(bprm);
1459 out_files:
1460 if (displaced)
1461 reset_files_struct(displaced);
1462 out_ret:
1463 return retval;
1466 void set_binfmt(struct linux_binfmt *new)
1468 struct mm_struct *mm = current->mm;
1470 if (mm->binfmt)
1471 module_put(mm->binfmt->module);
1473 mm->binfmt = new;
1474 if (new)
1475 __module_get(new->module);
1478 EXPORT_SYMBOL(set_binfmt);
1480 /* format_corename will inspect the pattern parameter, and output a
1481 * name into corename, which must have space for at least
1482 * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
1484 static int format_corename(char *corename, long signr)
1486 const struct cred *cred = current_cred();
1487 const char *pat_ptr = core_pattern;
1488 int ispipe = (*pat_ptr == '|');
1489 char *out_ptr = corename;
1490 char *const out_end = corename + CORENAME_MAX_SIZE;
1491 int rc;
1492 int pid_in_pattern = 0;
1494 /* Repeat as long as we have more pattern to process and more output
1495 space */
1496 while (*pat_ptr) {
1497 if (*pat_ptr != '%') {
1498 if (out_ptr == out_end)
1499 goto out;
1500 *out_ptr++ = *pat_ptr++;
1501 } else {
1502 switch (*++pat_ptr) {
1503 case 0:
1504 goto out;
1505 /* Double percent, output one percent */
1506 case '%':
1507 if (out_ptr == out_end)
1508 goto out;
1509 *out_ptr++ = '%';
1510 break;
1511 /* pid */
1512 case 'p':
1513 pid_in_pattern = 1;
1514 rc = snprintf(out_ptr, out_end - out_ptr,
1515 "%d", task_tgid_vnr(current));
1516 if (rc > out_end - out_ptr)
1517 goto out;
1518 out_ptr += rc;
1519 break;
1520 /* uid */
1521 case 'u':
1522 rc = snprintf(out_ptr, out_end - out_ptr,
1523 "%d", cred->uid);
1524 if (rc > out_end - out_ptr)
1525 goto out;
1526 out_ptr += rc;
1527 break;
1528 /* gid */
1529 case 'g':
1530 rc = snprintf(out_ptr, out_end - out_ptr,
1531 "%d", cred->gid);
1532 if (rc > out_end - out_ptr)
1533 goto out;
1534 out_ptr += rc;
1535 break;
1536 /* signal that caused the coredump */
1537 case 's':
1538 rc = snprintf(out_ptr, out_end - out_ptr,
1539 "%ld", signr);
1540 if (rc > out_end - out_ptr)
1541 goto out;
1542 out_ptr += rc;
1543 break;
1544 /* UNIX time of coredump */
1545 case 't': {
1546 struct timeval tv;
1547 do_gettimeofday(&tv);
1548 rc = snprintf(out_ptr, out_end - out_ptr,
1549 "%lu", tv.tv_sec);
1550 if (rc > out_end - out_ptr)
1551 goto out;
1552 out_ptr += rc;
1553 break;
1555 /* hostname */
1556 case 'h':
1557 down_read(&uts_sem);
1558 rc = snprintf(out_ptr, out_end - out_ptr,
1559 "%s", utsname()->nodename);
1560 up_read(&uts_sem);
1561 if (rc > out_end - out_ptr)
1562 goto out;
1563 out_ptr += rc;
1564 break;
1565 /* executable */
1566 case 'e':
1567 rc = snprintf(out_ptr, out_end - out_ptr,
1568 "%s", current->comm);
1569 if (rc > out_end - out_ptr)
1570 goto out;
1571 out_ptr += rc;
1572 break;
1573 /* core limit size */
1574 case 'c':
1575 rc = snprintf(out_ptr, out_end - out_ptr,
1576 "%lu", current->signal->rlim[RLIMIT_CORE].rlim_cur);
1577 if (rc > out_end - out_ptr)
1578 goto out;
1579 out_ptr += rc;
1580 break;
1581 default:
1582 break;
1584 ++pat_ptr;
1587 /* Backward compatibility with core_uses_pid:
1589 * If core_pattern does not include a %p (as is the default)
1590 * and core_uses_pid is set, then .%pid will be appended to
1591 * the filename. Do not do this for piped commands. */
1592 if (!ispipe && !pid_in_pattern && core_uses_pid) {
1593 rc = snprintf(out_ptr, out_end - out_ptr,
1594 ".%d", task_tgid_vnr(current));
1595 if (rc > out_end - out_ptr)
1596 goto out;
1597 out_ptr += rc;
1599 out:
1600 *out_ptr = 0;
1601 return ispipe;
1604 static int zap_process(struct task_struct *start)
1606 struct task_struct *t;
1607 int nr = 0;
1609 start->signal->flags = SIGNAL_GROUP_EXIT;
1610 start->signal->group_stop_count = 0;
1612 t = start;
1613 do {
1614 if (t != current && t->mm) {
1615 sigaddset(&t->pending.signal, SIGKILL);
1616 signal_wake_up(t, 1);
1617 nr++;
1619 } while_each_thread(start, t);
1621 return nr;
1624 static inline int zap_threads(struct task_struct *tsk, struct mm_struct *mm,
1625 struct core_state *core_state, int exit_code)
1627 struct task_struct *g, *p;
1628 unsigned long flags;
1629 int nr = -EAGAIN;
1631 spin_lock_irq(&tsk->sighand->siglock);
1632 if (!signal_group_exit(tsk->signal)) {
1633 mm->core_state = core_state;
1634 tsk->signal->group_exit_code = exit_code;
1635 nr = zap_process(tsk);
1637 spin_unlock_irq(&tsk->sighand->siglock);
1638 if (unlikely(nr < 0))
1639 return nr;
1641 if (atomic_read(&mm->mm_users) == nr + 1)
1642 goto done;
1644 * We should find and kill all tasks which use this mm, and we should
1645 * count them correctly into ->nr_threads. We don't take tasklist
1646 * lock, but this is safe wrt:
1648 * fork:
1649 * None of sub-threads can fork after zap_process(leader). All
1650 * processes which were created before this point should be
1651 * visible to zap_threads() because copy_process() adds the new
1652 * process to the tail of init_task.tasks list, and lock/unlock
1653 * of ->siglock provides a memory barrier.
1655 * do_exit:
1656 * The caller holds mm->mmap_sem. This means that the task which
1657 * uses this mm can't pass exit_mm(), so it can't exit or clear
1658 * its ->mm.
1660 * de_thread:
1661 * It does list_replace_rcu(&leader->tasks, &current->tasks),
1662 * we must see either old or new leader, this does not matter.
1663 * However, it can change p->sighand, so lock_task_sighand(p)
1664 * must be used. Since p->mm != NULL and we hold ->mmap_sem
1665 * it can't fail.
1667 * Note also that "g" can be the old leader with ->mm == NULL
1668 * and already unhashed and thus removed from ->thread_group.
1669 * This is OK, __unhash_process()->list_del_rcu() does not
1670 * clear the ->next pointer, we will find the new leader via
1671 * next_thread().
1673 rcu_read_lock();
1674 for_each_process(g) {
1675 if (g == tsk->group_leader)
1676 continue;
1677 if (g->flags & PF_KTHREAD)
1678 continue;
1679 p = g;
1680 do {
1681 if (p->mm) {
1682 if (unlikely(p->mm == mm)) {
1683 lock_task_sighand(p, &flags);
1684 nr += zap_process(p);
1685 unlock_task_sighand(p, &flags);
1687 break;
1689 } while_each_thread(g, p);
1691 rcu_read_unlock();
1692 done:
1693 atomic_set(&core_state->nr_threads, nr);
1694 return nr;
1697 static int coredump_wait(int exit_code, struct core_state *core_state)
1699 struct task_struct *tsk = current;
1700 struct mm_struct *mm = tsk->mm;
1701 struct completion *vfork_done;
1702 int core_waiters;
1704 init_completion(&core_state->startup);
1705 core_state->dumper.task = tsk;
1706 core_state->dumper.next = NULL;
1707 core_waiters = zap_threads(tsk, mm, core_state, exit_code);
1708 up_write(&mm->mmap_sem);
1710 if (unlikely(core_waiters < 0))
1711 goto fail;
1714 * Make sure nobody is waiting for us to release the VM,
1715 * otherwise we can deadlock when we wait on each other
1717 vfork_done = tsk->vfork_done;
1718 if (vfork_done) {
1719 tsk->vfork_done = NULL;
1720 complete(vfork_done);
1723 if (core_waiters)
1724 wait_for_completion(&core_state->startup);
1725 fail:
1726 return core_waiters;
1729 static void coredump_finish(struct mm_struct *mm)
1731 struct core_thread *curr, *next;
1732 struct task_struct *task;
1734 next = mm->core_state->dumper.next;
1735 while ((curr = next) != NULL) {
1736 next = curr->next;
1737 task = curr->task;
1739 * see exit_mm(), curr->task must not see
1740 * ->task == NULL before we read ->next.
1742 smp_mb();
1743 curr->task = NULL;
1744 wake_up_process(task);
1747 mm->core_state = NULL;
1751 * set_dumpable converts traditional three-value dumpable to two flags and
1752 * stores them into mm->flags. It modifies lower two bits of mm->flags, but
1753 * these bits are not changed atomically. So get_dumpable can observe the
1754 * intermediate state. To avoid doing unexpected behavior, get get_dumpable
1755 * return either old dumpable or new one by paying attention to the order of
1756 * modifying the bits.
1758 * dumpable | mm->flags (binary)
1759 * old new | initial interim final
1760 * ---------+-----------------------
1761 * 0 1 | 00 01 01
1762 * 0 2 | 00 10(*) 11
1763 * 1 0 | 01 00 00
1764 * 1 2 | 01 11 11
1765 * 2 0 | 11 10(*) 00
1766 * 2 1 | 11 11 01
1768 * (*) get_dumpable regards interim value of 10 as 11.
1770 void set_dumpable(struct mm_struct *mm, int value)
1772 switch (value) {
1773 case 0:
1774 clear_bit(MMF_DUMPABLE, &mm->flags);
1775 smp_wmb();
1776 clear_bit(MMF_DUMP_SECURELY, &mm->flags);
1777 break;
1778 case 1:
1779 set_bit(MMF_DUMPABLE, &mm->flags);
1780 smp_wmb();
1781 clear_bit(MMF_DUMP_SECURELY, &mm->flags);
1782 break;
1783 case 2:
1784 set_bit(MMF_DUMP_SECURELY, &mm->flags);
1785 smp_wmb();
1786 set_bit(MMF_DUMPABLE, &mm->flags);
1787 break;
1791 int get_dumpable(struct mm_struct *mm)
1793 int ret;
1795 ret = mm->flags & 0x3;
1796 return (ret >= 2) ? 2 : ret;
1799 static void wait_for_dump_helpers(struct file *file)
1801 struct pipe_inode_info *pipe;
1803 pipe = file->f_path.dentry->d_inode->i_pipe;
1805 pipe_lock(pipe);
1806 pipe->readers++;
1807 pipe->writers--;
1809 while ((pipe->readers > 1) && (!signal_pending(current))) {
1810 wake_up_interruptible_sync(&pipe->wait);
1811 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
1812 pipe_wait(pipe);
1815 pipe->readers--;
1816 pipe->writers++;
1817 pipe_unlock(pipe);
1822 void do_coredump(long signr, int exit_code, struct pt_regs *regs)
1824 struct core_state core_state;
1825 char corename[CORENAME_MAX_SIZE + 1];
1826 struct mm_struct *mm = current->mm;
1827 struct linux_binfmt * binfmt;
1828 struct inode * inode;
1829 const struct cred *old_cred;
1830 struct cred *cred;
1831 int retval = 0;
1832 int flag = 0;
1833 int ispipe = 0;
1834 char **helper_argv = NULL;
1835 int helper_argc = 0;
1836 int dump_count = 0;
1837 static atomic_t core_dump_count = ATOMIC_INIT(0);
1838 struct coredump_params cprm = {
1839 .signr = signr,
1840 .regs = regs,
1841 .limit = current->signal->rlim[RLIMIT_CORE].rlim_cur,
1844 audit_core_dumps(signr);
1846 binfmt = mm->binfmt;
1847 if (!binfmt || !binfmt->core_dump)
1848 goto fail;
1850 cred = prepare_creds();
1851 if (!cred) {
1852 retval = -ENOMEM;
1853 goto fail;
1856 down_write(&mm->mmap_sem);
1858 * If another thread got here first, or we are not dumpable, bail out.
1860 if (mm->core_state || !get_dumpable(mm)) {
1861 up_write(&mm->mmap_sem);
1862 put_cred(cred);
1863 goto fail;
1867 * We cannot trust fsuid as being the "true" uid of the
1868 * process nor do we know its entire history. We only know it
1869 * was tainted so we dump it as root in mode 2.
1871 if (get_dumpable(mm) == 2) { /* Setuid core dump mode */
1872 flag = O_EXCL; /* Stop rewrite attacks */
1873 cred->fsuid = 0; /* Dump root private */
1876 retval = coredump_wait(exit_code, &core_state);
1877 if (retval < 0) {
1878 put_cred(cred);
1879 goto fail;
1882 old_cred = override_creds(cred);
1885 * Clear any false indication of pending signals that might
1886 * be seen by the filesystem code called to write the core file.
1888 clear_thread_flag(TIF_SIGPENDING);
1891 * lock_kernel() because format_corename() is controlled by sysctl, which
1892 * uses lock_kernel()
1894 lock_kernel();
1895 ispipe = format_corename(corename, signr);
1896 unlock_kernel();
1898 if ((!ispipe) && (cprm.limit < binfmt->min_coredump))
1899 goto fail_unlock;
1901 if (ispipe) {
1902 if (cprm.limit == 0) {
1904 * Normally core limits are irrelevant to pipes, since
1905 * we're not writing to the file system, but we use
1906 * cprm.limit of 0 here as a speacial value. Any
1907 * non-zero limit gets set to RLIM_INFINITY below, but
1908 * a limit of 0 skips the dump. This is a consistent
1909 * way to catch recursive crashes. We can still crash
1910 * if the core_pattern binary sets RLIM_CORE = !0
1911 * but it runs as root, and can do lots of stupid things
1912 * Note that we use task_tgid_vnr here to grab the pid
1913 * of the process group leader. That way we get the
1914 * right pid if a thread in a multi-threaded
1915 * core_pattern process dies.
1917 printk(KERN_WARNING
1918 "Process %d(%s) has RLIMIT_CORE set to 0\n",
1919 task_tgid_vnr(current), current->comm);
1920 printk(KERN_WARNING "Aborting core\n");
1921 goto fail_unlock;
1924 dump_count = atomic_inc_return(&core_dump_count);
1925 if (core_pipe_limit && (core_pipe_limit < dump_count)) {
1926 printk(KERN_WARNING "Pid %d(%s) over core_pipe_limit\n",
1927 task_tgid_vnr(current), current->comm);
1928 printk(KERN_WARNING "Skipping core dump\n");
1929 goto fail_dropcount;
1932 helper_argv = argv_split(GFP_KERNEL, corename+1, &helper_argc);
1933 if (!helper_argv) {
1934 printk(KERN_WARNING "%s failed to allocate memory\n",
1935 __func__);
1936 goto fail_dropcount;
1939 cprm.limit = RLIM_INFINITY;
1941 /* SIGPIPE can happen, but it's just never processed */
1942 if (call_usermodehelper_pipe(helper_argv[0], helper_argv, NULL,
1943 &cprm.file)) {
1944 printk(KERN_INFO "Core dump to %s pipe failed\n",
1945 corename);
1946 goto fail_dropcount;
1948 } else
1949 cprm.file = filp_open(corename,
1950 O_CREAT | 2 | O_NOFOLLOW | O_LARGEFILE | flag,
1951 0600);
1952 if (IS_ERR(cprm.file))
1953 goto fail_dropcount;
1954 inode = cprm.file->f_path.dentry->d_inode;
1955 if (inode->i_nlink > 1)
1956 goto close_fail; /* multiple links - don't dump */
1957 if (!ispipe && d_unhashed(cprm.file->f_path.dentry))
1958 goto close_fail;
1960 /* AK: actually i see no reason to not allow this for named pipes etc.,
1961 but keep the previous behaviour for now. */
1962 if (!ispipe && !S_ISREG(inode->i_mode))
1963 goto close_fail;
1965 * Dont allow local users get cute and trick others to coredump
1966 * into their pre-created files:
1967 * Note, this is not relevant for pipes
1969 if (!ispipe && (inode->i_uid != current_fsuid()))
1970 goto close_fail;
1971 if (!cprm.file->f_op)
1972 goto close_fail;
1973 if (!cprm.file->f_op->write)
1974 goto close_fail;
1975 if (!ispipe &&
1976 do_truncate(cprm.file->f_path.dentry, 0, 0, cprm.file) != 0)
1977 goto close_fail;
1979 retval = binfmt->core_dump(&cprm);
1981 if (retval)
1982 current->signal->group_exit_code |= 0x80;
1983 close_fail:
1984 if (ispipe && core_pipe_limit)
1985 wait_for_dump_helpers(cprm.file);
1986 filp_close(cprm.file, NULL);
1987 fail_dropcount:
1988 if (dump_count)
1989 atomic_dec(&core_dump_count);
1990 fail_unlock:
1991 if (helper_argv)
1992 argv_free(helper_argv);
1994 revert_creds(old_cred);
1995 put_cred(cred);
1996 coredump_finish(mm);
1997 fail:
1998 return;