ocfs2: fix start offset to ocfs2_zero_range_for_truncate()
[pandora-kernel.git] / fs / exec.c
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/swap.h>
32 #include <linux/string.h>
33 #include <linux/init.h>
34 #include <linux/pagemap.h>
35 #include <linux/perf_event.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/mount.h>
46 #include <linux/security.h>
47 #include <linux/syscalls.h>
48 #include <linux/tsacct_kern.h>
49 #include <linux/cn_proc.h>
50 #include <linux/audit.h>
51 #include <linux/tracehook.h>
52 #include <linux/kmod.h>
53 #include <linux/fsnotify.h>
54 #include <linux/fs_struct.h>
55 #include <linux/pipe_fs_i.h>
56 #include <linux/oom.h>
57 #include <linux/compat.h>
58 #include <linux/sched.h>
59 #include <linux/fs.h>
60 #include <linux/path.h>
61
62 #include <asm/uaccess.h>
63 #include <asm/mmu_context.h>
64 #include <asm/tlb.h>
65 #include "internal.h"
66
67 int core_uses_pid;
68 char core_pattern[CORENAME_MAX_SIZE] = "core";
69 unsigned int core_pipe_limit;
70 int suid_dumpable = 0;
71
72 struct core_name {
73         char *corename;
74         int used, size;
75 };
76 static atomic_t call_count = ATOMIC_INIT(1);
77
78 /* The maximal length of core_pattern is also specified in sysctl.c */
79
80 static LIST_HEAD(formats);
81 static DEFINE_RWLOCK(binfmt_lock);
82
83 int __register_binfmt(struct linux_binfmt * fmt, int insert)
84 {
85         if (!fmt)
86                 return -EINVAL;
87         write_lock(&binfmt_lock);
88         insert ? list_add(&fmt->lh, &formats) :
89                  list_add_tail(&fmt->lh, &formats);
90         write_unlock(&binfmt_lock);
91         return 0;       
92 }
93
94 EXPORT_SYMBOL(__register_binfmt);
95
96 void unregister_binfmt(struct linux_binfmt * fmt)
97 {
98         write_lock(&binfmt_lock);
99         list_del(&fmt->lh);
100         write_unlock(&binfmt_lock);
101 }
102
103 EXPORT_SYMBOL(unregister_binfmt);
104
105 static inline void put_binfmt(struct linux_binfmt * fmt)
106 {
107         module_put(fmt->module);
108 }
109
110 /*
111  * Note that a shared library must be both readable and executable due to
112  * security reasons.
113  *
114  * Also note that we take the address to load from from the file itself.
115  */
116 SYSCALL_DEFINE1(uselib, const char __user *, library)
117 {
118         struct file *file;
119         char *tmp = getname(library);
120         int error = PTR_ERR(tmp);
121         static const struct open_flags uselib_flags = {
122                 .open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC,
123                 .acc_mode = MAY_READ | MAY_EXEC | MAY_OPEN,
124                 .intent = LOOKUP_OPEN
125         };
126
127         if (IS_ERR(tmp))
128                 goto out;
129
130         file = do_filp_open(AT_FDCWD, tmp, &uselib_flags, LOOKUP_FOLLOW);
131         putname(tmp);
132         error = PTR_ERR(file);
133         if (IS_ERR(file))
134                 goto out;
135
136         error = -EINVAL;
137         if (!S_ISREG(file->f_path.dentry->d_inode->i_mode))
138                 goto exit;
139
140         error = -EACCES;
141         if (file->f_path.mnt->mnt_flags & MNT_NOEXEC)
142                 goto exit;
143
144         fsnotify_open(file);
145
146         error = -ENOEXEC;
147         if(file->f_op) {
148                 struct linux_binfmt * fmt;
149
150                 read_lock(&binfmt_lock);
151                 list_for_each_entry(fmt, &formats, lh) {
152                         if (!fmt->load_shlib)
153                                 continue;
154                         if (!try_module_get(fmt->module))
155                                 continue;
156                         read_unlock(&binfmt_lock);
157                         error = fmt->load_shlib(file);
158                         read_lock(&binfmt_lock);
159                         put_binfmt(fmt);
160                         if (error != -ENOEXEC)
161                                 break;
162                 }
163                 read_unlock(&binfmt_lock);
164         }
165 exit:
166         fput(file);
167 out:
168         return error;
169 }
170
171 #ifdef CONFIG_MMU
172 /*
173  * The nascent bprm->mm is not visible until exec_mmap() but it can
174  * use a lot of memory, account these pages in current->mm temporary
175  * for oom_badness()->get_mm_rss(). Once exec succeeds or fails, we
176  * change the counter back via acct_arg_size(0).
177  */
178 static void acct_arg_size(struct linux_binprm *bprm, unsigned long pages)
179 {
180         struct mm_struct *mm = current->mm;
181         long diff = (long)(pages - bprm->vma_pages);
182
183         if (!mm || !diff)
184                 return;
185
186         bprm->vma_pages = pages;
187         add_mm_counter(mm, MM_ANONPAGES, diff);
188 }
189
190 static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
191                 int write)
192 {
193         struct page *page;
194         int ret;
195
196 #ifdef CONFIG_STACK_GROWSUP
197         if (write) {
198                 ret = expand_downwards(bprm->vma, pos);
199                 if (ret < 0)
200                         return NULL;
201         }
202 #endif
203         ret = get_user_pages(current, bprm->mm, pos,
204                         1, write, 1, &page, NULL);
205         if (ret <= 0)
206                 return NULL;
207
208         if (write) {
209                 unsigned long size = bprm->vma->vm_end - bprm->vma->vm_start;
210                 struct rlimit *rlim;
211
212                 acct_arg_size(bprm, size / PAGE_SIZE);
213
214                 /*
215                  * We've historically supported up to 32 pages (ARG_MAX)
216                  * of argument strings even with small stacks
217                  */
218                 if (size <= ARG_MAX)
219                         return page;
220
221                 /*
222                  * Limit to 1/4-th the stack size for the argv+env strings.
223                  * This ensures that:
224                  *  - the remaining binfmt code will not run out of stack space,
225                  *  - the program will have a reasonable amount of stack left
226                  *    to work from.
227                  */
228                 rlim = current->signal->rlim;
229                 if (size > ACCESS_ONCE(rlim[RLIMIT_STACK].rlim_cur) / 4) {
230                         put_page(page);
231                         return NULL;
232                 }
233         }
234
235         return page;
236 }
237
238 static void put_arg_page(struct page *page)
239 {
240         put_page(page);
241 }
242
243 static void free_arg_page(struct linux_binprm *bprm, int i)
244 {
245 }
246
247 static void free_arg_pages(struct linux_binprm *bprm)
248 {
249 }
250
251 static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
252                 struct page *page)
253 {
254         flush_cache_page(bprm->vma, pos, page_to_pfn(page));
255 }
256
257 static int __bprm_mm_init(struct linux_binprm *bprm)
258 {
259         int err;
260         struct vm_area_struct *vma = NULL;
261         struct mm_struct *mm = bprm->mm;
262
263         bprm->vma = vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
264         if (!vma)
265                 return -ENOMEM;
266
267         down_write(&mm->mmap_sem);
268         vma->vm_mm = mm;
269
270         /*
271          * Place the stack at the largest stack address the architecture
272          * supports. Later, we'll move this to an appropriate place. We don't
273          * use STACK_TOP because that can depend on attributes which aren't
274          * configured yet.
275          */
276         BUILD_BUG_ON(VM_STACK_FLAGS & VM_STACK_INCOMPLETE_SETUP);
277         vma->vm_end = STACK_TOP_MAX;
278         vma->vm_start = vma->vm_end - PAGE_SIZE;
279         vma->vm_flags = VM_STACK_FLAGS | VM_STACK_INCOMPLETE_SETUP;
280         vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
281         INIT_LIST_HEAD(&vma->anon_vma_chain);
282
283         err = security_file_mmap(NULL, 0, 0, 0, vma->vm_start, 1);
284         if (err)
285                 goto err;
286
287         err = insert_vm_struct(mm, vma);
288         if (err)
289                 goto err;
290
291         mm->stack_vm = mm->total_vm = 1;
292         up_write(&mm->mmap_sem);
293         bprm->p = vma->vm_end - sizeof(void *);
294         return 0;
295 err:
296         up_write(&mm->mmap_sem);
297         bprm->vma = NULL;
298         kmem_cache_free(vm_area_cachep, vma);
299         return err;
300 }
301
302 static bool valid_arg_len(struct linux_binprm *bprm, long len)
303 {
304         return len <= MAX_ARG_STRLEN;
305 }
306
307 #else
308
309 static inline void acct_arg_size(struct linux_binprm *bprm, unsigned long pages)
310 {
311 }
312
313 static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
314                 int write)
315 {
316         struct page *page;
317
318         page = bprm->page[pos / PAGE_SIZE];
319         if (!page && write) {
320                 page = alloc_page(GFP_HIGHUSER|__GFP_ZERO);
321                 if (!page)
322                         return NULL;
323                 bprm->page[pos / PAGE_SIZE] = page;
324         }
325
326         return page;
327 }
328
329 static void put_arg_page(struct page *page)
330 {
331 }
332
333 static void free_arg_page(struct linux_binprm *bprm, int i)
334 {
335         if (bprm->page[i]) {
336                 __free_page(bprm->page[i]);
337                 bprm->page[i] = NULL;
338         }
339 }
340
341 static void free_arg_pages(struct linux_binprm *bprm)
342 {
343         int i;
344
345         for (i = 0; i < MAX_ARG_PAGES; i++)
346                 free_arg_page(bprm, i);
347 }
348
349 static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
350                 struct page *page)
351 {
352 }
353
354 static int __bprm_mm_init(struct linux_binprm *bprm)
355 {
356         bprm->p = PAGE_SIZE * MAX_ARG_PAGES - sizeof(void *);
357         return 0;
358 }
359
360 static bool valid_arg_len(struct linux_binprm *bprm, long len)
361 {
362         return len <= bprm->p;
363 }
364
365 #endif /* CONFIG_MMU */
366
367 /*
368  * Create a new mm_struct and populate it with a temporary stack
369  * vm_area_struct.  We don't have enough context at this point to set the stack
370  * flags, permissions, and offset, so we use temporary values.  We'll update
371  * them later in setup_arg_pages().
372  */
373 int bprm_mm_init(struct linux_binprm *bprm)
374 {
375         int err;
376         struct mm_struct *mm = NULL;
377
378         bprm->mm = mm = mm_alloc();
379         err = -ENOMEM;
380         if (!mm)
381                 goto err;
382
383         err = init_new_context(current, mm);
384         if (err)
385                 goto err;
386
387         err = __bprm_mm_init(bprm);
388         if (err)
389                 goto err;
390
391         return 0;
392
393 err:
394         if (mm) {
395                 bprm->mm = NULL;
396                 mmdrop(mm);
397         }
398
399         return err;
400 }
401
402 struct user_arg_ptr {
403 #ifdef CONFIG_COMPAT
404         bool is_compat;
405 #endif
406         union {
407                 const char __user *const __user *native;
408 #ifdef CONFIG_COMPAT
409                 compat_uptr_t __user *compat;
410 #endif
411         } ptr;
412 };
413
414 static const char __user *get_user_arg_ptr(struct user_arg_ptr argv, int nr)
415 {
416         const char __user *native;
417
418 #ifdef CONFIG_COMPAT
419         if (unlikely(argv.is_compat)) {
420                 compat_uptr_t compat;
421
422                 if (get_user(compat, argv.ptr.compat + nr))
423                         return ERR_PTR(-EFAULT);
424
425                 return compat_ptr(compat);
426         }
427 #endif
428
429         if (get_user(native, argv.ptr.native + nr))
430                 return ERR_PTR(-EFAULT);
431
432         return native;
433 }
434
435 /*
436  * count() counts the number of strings in array ARGV.
437  */
438 static int count(struct user_arg_ptr argv, int max)
439 {
440         int i = 0;
441
442         if (argv.ptr.native != NULL) {
443                 for (;;) {
444                         const char __user *p = get_user_arg_ptr(argv, i);
445
446                         if (!p)
447                                 break;
448
449                         if (IS_ERR(p))
450                                 return -EFAULT;
451
452                         if (i++ >= max)
453                                 return -E2BIG;
454
455                         if (fatal_signal_pending(current))
456                                 return -ERESTARTNOHAND;
457                         cond_resched();
458                 }
459         }
460         return i;
461 }
462
463 /*
464  * 'copy_strings()' copies argument/environment strings from the old
465  * processes's memory to the new process's stack.  The call to get_user_pages()
466  * ensures the destination page is created and not swapped out.
467  */
468 static int copy_strings(int argc, struct user_arg_ptr argv,
469                         struct linux_binprm *bprm)
470 {
471         struct page *kmapped_page = NULL;
472         char *kaddr = NULL;
473         unsigned long kpos = 0;
474         int ret;
475
476         while (argc-- > 0) {
477                 const char __user *str;
478                 int len;
479                 unsigned long pos;
480
481                 ret = -EFAULT;
482                 str = get_user_arg_ptr(argv, argc);
483                 if (IS_ERR(str))
484                         goto out;
485
486                 len = strnlen_user(str, MAX_ARG_STRLEN);
487                 if (!len)
488                         goto out;
489
490                 ret = -E2BIG;
491                 if (!valid_arg_len(bprm, len))
492                         goto out;
493
494                 /* We're going to work our way backwords. */
495                 pos = bprm->p;
496                 str += len;
497                 bprm->p -= len;
498
499                 while (len > 0) {
500                         int offset, bytes_to_copy;
501
502                         if (fatal_signal_pending(current)) {
503                                 ret = -ERESTARTNOHAND;
504                                 goto out;
505                         }
506                         cond_resched();
507
508                         offset = pos % PAGE_SIZE;
509                         if (offset == 0)
510                                 offset = PAGE_SIZE;
511
512                         bytes_to_copy = offset;
513                         if (bytes_to_copy > len)
514                                 bytes_to_copy = len;
515
516                         offset -= bytes_to_copy;
517                         pos -= bytes_to_copy;
518                         str -= bytes_to_copy;
519                         len -= bytes_to_copy;
520
521                         if (!kmapped_page || kpos != (pos & PAGE_MASK)) {
522                                 struct page *page;
523
524                                 page = get_arg_page(bprm, pos, 1);
525                                 if (!page) {
526                                         ret = -E2BIG;
527                                         goto out;
528                                 }
529
530                                 if (kmapped_page) {
531                                         flush_kernel_dcache_page(kmapped_page);
532                                         kunmap(kmapped_page);
533                                         put_arg_page(kmapped_page);
534                                 }
535                                 kmapped_page = page;
536                                 kaddr = kmap(kmapped_page);
537                                 kpos = pos & PAGE_MASK;
538                                 flush_arg_page(bprm, kpos, kmapped_page);
539                         }
540                         if (copy_from_user(kaddr+offset, str, bytes_to_copy)) {
541                                 ret = -EFAULT;
542                                 goto out;
543                         }
544                 }
545         }
546         ret = 0;
547 out:
548         if (kmapped_page) {
549                 flush_kernel_dcache_page(kmapped_page);
550                 kunmap(kmapped_page);
551                 put_arg_page(kmapped_page);
552         }
553         return ret;
554 }
555
556 /*
557  * Like copy_strings, but get argv and its values from kernel memory.
558  */
559 int copy_strings_kernel(int argc, const char *const *__argv,
560                         struct linux_binprm *bprm)
561 {
562         int r;
563         mm_segment_t oldfs = get_fs();
564         struct user_arg_ptr argv = {
565                 .ptr.native = (const char __user *const  __user *)__argv,
566         };
567
568         set_fs(KERNEL_DS);
569         r = copy_strings(argc, argv, bprm);
570         set_fs(oldfs);
571
572         return r;
573 }
574 EXPORT_SYMBOL(copy_strings_kernel);
575
576 #ifdef CONFIG_MMU
577
578 /*
579  * During bprm_mm_init(), we create a temporary stack at STACK_TOP_MAX.  Once
580  * the binfmt code determines where the new stack should reside, we shift it to
581  * its final location.  The process proceeds as follows:
582  *
583  * 1) Use shift to calculate the new vma endpoints.
584  * 2) Extend vma to cover both the old and new ranges.  This ensures the
585  *    arguments passed to subsequent functions are consistent.
586  * 3) Move vma's page tables to the new range.
587  * 4) Free up any cleared pgd range.
588  * 5) Shrink the vma to cover only the new range.
589  */
590 static int shift_arg_pages(struct vm_area_struct *vma, unsigned long shift)
591 {
592         struct mm_struct *mm = vma->vm_mm;
593         unsigned long old_start = vma->vm_start;
594         unsigned long old_end = vma->vm_end;
595         unsigned long length = old_end - old_start;
596         unsigned long new_start = old_start - shift;
597         unsigned long new_end = old_end - shift;
598         struct mmu_gather tlb;
599
600         BUG_ON(new_start > new_end);
601
602         /*
603          * ensure there are no vmas between where we want to go
604          * and where we are
605          */
606         if (vma != find_vma(mm, new_start))
607                 return -EFAULT;
608
609         /*
610          * cover the whole range: [new_start, old_end)
611          */
612         if (vma_adjust(vma, new_start, old_end, vma->vm_pgoff, NULL))
613                 return -ENOMEM;
614
615         /*
616          * move the page tables downwards, on failure we rely on
617          * process cleanup to remove whatever mess we made.
618          */
619         if (length != move_page_tables(vma, old_start,
620                                        vma, new_start, length))
621                 return -ENOMEM;
622
623         lru_add_drain();
624         tlb_gather_mmu(&tlb, mm, 0);
625         if (new_end > old_start) {
626                 /*
627                  * when the old and new regions overlap clear from new_end.
628                  */
629                 free_pgd_range(&tlb, new_end, old_end, new_end,
630                         vma->vm_next ? vma->vm_next->vm_start : 0);
631         } else {
632                 /*
633                  * otherwise, clean from old_start; this is done to not touch
634                  * the address space in [new_end, old_start) some architectures
635                  * have constraints on va-space that make this illegal (IA64) -
636                  * for the others its just a little faster.
637                  */
638                 free_pgd_range(&tlb, old_start, old_end, new_end,
639                         vma->vm_next ? vma->vm_next->vm_start : 0);
640         }
641         tlb_finish_mmu(&tlb, new_end, old_end);
642
643         /*
644          * Shrink the vma to just the new range.  Always succeeds.
645          */
646         vma_adjust(vma, new_start, new_end, vma->vm_pgoff, NULL);
647
648         return 0;
649 }
650
651 /*
652  * Finalizes the stack vm_area_struct. The flags and permissions are updated,
653  * the stack is optionally relocated, and some extra space is added.
654  */
655 int setup_arg_pages(struct linux_binprm *bprm,
656                     unsigned long stack_top,
657                     int executable_stack)
658 {
659         unsigned long ret;
660         unsigned long stack_shift;
661         struct mm_struct *mm = current->mm;
662         struct vm_area_struct *vma = bprm->vma;
663         struct vm_area_struct *prev = NULL;
664         unsigned long vm_flags;
665         unsigned long stack_base;
666         unsigned long stack_size;
667         unsigned long stack_expand;
668         unsigned long rlim_stack;
669
670 #ifdef CONFIG_STACK_GROWSUP
671         /* Limit stack size to 1GB */
672         stack_base = rlimit_max(RLIMIT_STACK);
673         if (stack_base > (1 << 30))
674                 stack_base = 1 << 30;
675
676         /* Make sure we didn't let the argument array grow too large. */
677         if (vma->vm_end - vma->vm_start > stack_base)
678                 return -ENOMEM;
679
680         stack_base = PAGE_ALIGN(stack_top - stack_base);
681
682         stack_shift = vma->vm_start - stack_base;
683         mm->arg_start = bprm->p - stack_shift;
684         bprm->p = vma->vm_end - stack_shift;
685 #else
686         stack_top = arch_align_stack(stack_top);
687         stack_top = PAGE_ALIGN(stack_top);
688
689         if (unlikely(stack_top < mmap_min_addr) ||
690             unlikely(vma->vm_end - vma->vm_start >= stack_top - mmap_min_addr))
691                 return -ENOMEM;
692
693         stack_shift = vma->vm_end - stack_top;
694
695         bprm->p -= stack_shift;
696         mm->arg_start = bprm->p;
697 #endif
698
699         if (bprm->loader)
700                 bprm->loader -= stack_shift;
701         bprm->exec -= stack_shift;
702
703         down_write(&mm->mmap_sem);
704         vm_flags = VM_STACK_FLAGS;
705
706         /*
707          * Adjust stack execute permissions; explicitly enable for
708          * EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X and leave alone
709          * (arch default) otherwise.
710          */
711         if (unlikely(executable_stack == EXSTACK_ENABLE_X))
712                 vm_flags |= VM_EXEC;
713         else if (executable_stack == EXSTACK_DISABLE_X)
714                 vm_flags &= ~VM_EXEC;
715         vm_flags |= mm->def_flags;
716         vm_flags |= VM_STACK_INCOMPLETE_SETUP;
717
718         ret = mprotect_fixup(vma, &prev, vma->vm_start, vma->vm_end,
719                         vm_flags);
720         if (ret)
721                 goto out_unlock;
722         BUG_ON(prev != vma);
723
724         /* Move stack pages down in memory. */
725         if (stack_shift) {
726                 ret = shift_arg_pages(vma, stack_shift);
727                 if (ret)
728                         goto out_unlock;
729         }
730
731         /* mprotect_fixup is overkill to remove the temporary stack flags */
732         vma->vm_flags &= ~VM_STACK_INCOMPLETE_SETUP;
733
734         stack_expand = 131072UL; /* randomly 32*4k (or 2*64k) pages */
735         stack_size = vma->vm_end - vma->vm_start;
736         /*
737          * Align this down to a page boundary as expand_stack
738          * will align it up.
739          */
740         rlim_stack = rlimit(RLIMIT_STACK) & PAGE_MASK;
741 #ifdef CONFIG_STACK_GROWSUP
742         if (stack_size + stack_expand > rlim_stack)
743                 stack_base = vma->vm_start + rlim_stack;
744         else
745                 stack_base = vma->vm_end + stack_expand;
746 #else
747         if (stack_size + stack_expand > rlim_stack)
748                 stack_base = vma->vm_end - rlim_stack;
749         else
750                 stack_base = vma->vm_start - stack_expand;
751 #endif
752         current->mm->start_stack = bprm->p;
753         ret = expand_stack(vma, stack_base);
754         if (ret)
755                 ret = -EFAULT;
756
757 out_unlock:
758         up_write(&mm->mmap_sem);
759         return ret;
760 }
761 EXPORT_SYMBOL(setup_arg_pages);
762
763 #endif /* CONFIG_MMU */
764
765 struct file *open_exec(const char *name)
766 {
767         struct file *file;
768         int err;
769         static const struct open_flags open_exec_flags = {
770                 .open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC,
771                 .acc_mode = MAY_EXEC | MAY_OPEN,
772                 .intent = LOOKUP_OPEN
773         };
774
775         file = do_filp_open(AT_FDCWD, name, &open_exec_flags, LOOKUP_FOLLOW);
776         if (IS_ERR(file))
777                 goto out;
778
779         err = -EACCES;
780         if (!S_ISREG(file->f_path.dentry->d_inode->i_mode))
781                 goto exit;
782
783         if (file->f_path.mnt->mnt_flags & MNT_NOEXEC)
784                 goto exit;
785
786         fsnotify_open(file);
787
788         err = deny_write_access(file);
789         if (err)
790                 goto exit;
791
792 out:
793         return file;
794
795 exit:
796         fput(file);
797         return ERR_PTR(err);
798 }
799 EXPORT_SYMBOL(open_exec);
800
801 int kernel_read(struct file *file, loff_t offset,
802                 char *addr, unsigned long count)
803 {
804         mm_segment_t old_fs;
805         loff_t pos = offset;
806         int result;
807
808         old_fs = get_fs();
809         set_fs(get_ds());
810         /* The cast to a user pointer is valid due to the set_fs() */
811         result = vfs_read(file, (void __user *)addr, count, &pos);
812         set_fs(old_fs);
813         return result;
814 }
815
816 EXPORT_SYMBOL(kernel_read);
817
818 static int exec_mmap(struct mm_struct *mm)
819 {
820         struct task_struct *tsk;
821         struct mm_struct * old_mm, *active_mm;
822
823         /* Notify parent that we're no longer interested in the old VM */
824         tsk = current;
825         old_mm = current->mm;
826         sync_mm_rss(tsk, old_mm);
827         mm_release(tsk, old_mm);
828
829         if (old_mm) {
830                 /*
831                  * Make sure that if there is a core dump in progress
832                  * for the old mm, we get out and die instead of going
833                  * through with the exec.  We must hold mmap_sem around
834                  * checking core_state and changing tsk->mm.
835                  */
836                 down_read(&old_mm->mmap_sem);
837                 if (unlikely(old_mm->core_state)) {
838                         up_read(&old_mm->mmap_sem);
839                         return -EINTR;
840                 }
841         }
842         task_lock(tsk);
843         active_mm = tsk->active_mm;
844         tsk->mm = mm;
845         tsk->active_mm = mm;
846         activate_mm(active_mm, mm);
847         task_unlock(tsk);
848         arch_pick_mmap_layout(mm);
849         if (old_mm) {
850                 up_read(&old_mm->mmap_sem);
851                 BUG_ON(active_mm != old_mm);
852                 mm_update_next_owner(old_mm);
853                 mmput(old_mm);
854                 return 0;
855         }
856         mmdrop(active_mm);
857         return 0;
858 }
859
860 /*
861  * This function makes sure the current process has its own signal table,
862  * so that flush_signal_handlers can later reset the handlers without
863  * disturbing other processes.  (Other processes might share the signal
864  * table via the CLONE_SIGHAND option to clone().)
865  */
866 static int de_thread(struct task_struct *tsk)
867 {
868         struct signal_struct *sig = tsk->signal;
869         struct sighand_struct *oldsighand = tsk->sighand;
870         spinlock_t *lock = &oldsighand->siglock;
871
872         if (thread_group_empty(tsk))
873                 goto no_thread_group;
874
875         /*
876          * Kill all other threads in the thread group.
877          */
878         spin_lock_irq(lock);
879         if (signal_group_exit(sig)) {
880                 /*
881                  * Another group action in progress, just
882                  * return so that the signal is processed.
883                  */
884                 spin_unlock_irq(lock);
885                 return -EAGAIN;
886         }
887
888         sig->group_exit_task = tsk;
889         sig->notify_count = zap_other_threads(tsk);
890         if (!thread_group_leader(tsk))
891                 sig->notify_count--;
892
893         while (sig->notify_count) {
894                 __set_current_state(TASK_UNINTERRUPTIBLE);
895                 spin_unlock_irq(lock);
896                 schedule();
897                 spin_lock_irq(lock);
898         }
899         spin_unlock_irq(lock);
900
901         /*
902          * At this point all other threads have exited, all we have to
903          * do is to wait for the thread group leader to become inactive,
904          * and to assume its PID:
905          */
906         if (!thread_group_leader(tsk)) {
907                 struct task_struct *leader = tsk->group_leader;
908
909                 sig->notify_count = -1; /* for exit_notify() */
910                 for (;;) {
911                         write_lock_irq(&tasklist_lock);
912                         if (likely(leader->exit_state))
913                                 break;
914                         __set_current_state(TASK_UNINTERRUPTIBLE);
915                         write_unlock_irq(&tasklist_lock);
916                         schedule();
917                 }
918
919                 /*
920                  * The only record we have of the real-time age of a
921                  * process, regardless of execs it's done, is start_time.
922                  * All the past CPU time is accumulated in signal_struct
923                  * from sister threads now dead.  But in this non-leader
924                  * exec, nothing survives from the original leader thread,
925                  * whose birth marks the true age of this process now.
926                  * When we take on its identity by switching to its PID, we
927                  * also take its birthdate (always earlier than our own).
928                  */
929                 tsk->start_time = leader->start_time;
930
931                 BUG_ON(!same_thread_group(leader, tsk));
932                 BUG_ON(has_group_leader_pid(tsk));
933                 /*
934                  * An exec() starts a new thread group with the
935                  * TGID of the previous thread group. Rehash the
936                  * two threads with a switched PID, and release
937                  * the former thread group leader:
938                  */
939
940                 /* Become a process group leader with the old leader's pid.
941                  * The old leader becomes a thread of the this thread group.
942                  * Note: The old leader also uses this pid until release_task
943                  *       is called.  Odd but simple and correct.
944                  */
945                 detach_pid(tsk, PIDTYPE_PID);
946                 tsk->pid = leader->pid;
947                 attach_pid(tsk, PIDTYPE_PID,  task_pid(leader));
948                 transfer_pid(leader, tsk, PIDTYPE_PGID);
949                 transfer_pid(leader, tsk, PIDTYPE_SID);
950
951                 list_replace_rcu(&leader->tasks, &tsk->tasks);
952                 list_replace_init(&leader->sibling, &tsk->sibling);
953
954                 tsk->group_leader = tsk;
955                 leader->group_leader = tsk;
956
957                 tsk->exit_signal = SIGCHLD;
958                 leader->exit_signal = -1;
959
960                 BUG_ON(leader->exit_state != EXIT_ZOMBIE);
961                 leader->exit_state = EXIT_DEAD;
962
963                 /*
964                  * We are going to release_task()->ptrace_unlink() silently,
965                  * the tracer can sleep in do_wait(). EXIT_DEAD guarantees
966                  * the tracer wont't block again waiting for this thread.
967                  */
968                 if (unlikely(leader->ptrace))
969                         __wake_up_parent(leader, leader->parent);
970                 write_unlock_irq(&tasklist_lock);
971
972                 release_task(leader);
973         }
974
975         sig->group_exit_task = NULL;
976         sig->notify_count = 0;
977
978 no_thread_group:
979         /* we have changed execution domain */
980         tsk->exit_signal = SIGCHLD;
981
982         if (current->mm)
983                 setmax_mm_hiwater_rss(&sig->maxrss, current->mm);
984
985         exit_itimers(sig);
986         flush_itimer_signals();
987
988         if (atomic_read(&oldsighand->count) != 1) {
989                 struct sighand_struct *newsighand;
990                 /*
991                  * This ->sighand is shared with the CLONE_SIGHAND
992                  * but not CLONE_THREAD task, switch to the new one.
993                  */
994                 newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
995                 if (!newsighand)
996                         return -ENOMEM;
997
998                 atomic_set(&newsighand->count, 1);
999                 memcpy(newsighand->action, oldsighand->action,
1000                        sizeof(newsighand->action));
1001
1002                 write_lock_irq(&tasklist_lock);
1003                 spin_lock(&oldsighand->siglock);
1004                 rcu_assign_pointer(tsk->sighand, newsighand);
1005                 spin_unlock(&oldsighand->siglock);
1006                 write_unlock_irq(&tasklist_lock);
1007
1008                 __cleanup_sighand(oldsighand);
1009         }
1010
1011         BUG_ON(!thread_group_leader(tsk));
1012         return 0;
1013 }
1014
1015 /*
1016  * These functions flushes out all traces of the currently running executable
1017  * so that a new one can be started
1018  */
1019 static void flush_old_files(struct files_struct * files)
1020 {
1021         long j = -1;
1022         struct fdtable *fdt;
1023
1024         spin_lock(&files->file_lock);
1025         for (;;) {
1026                 unsigned long set, i;
1027
1028                 j++;
1029                 i = j * __NFDBITS;
1030                 fdt = files_fdtable(files);
1031                 if (i >= fdt->max_fds)
1032                         break;
1033                 set = fdt->close_on_exec->fds_bits[j];
1034                 if (!set)
1035                         continue;
1036                 fdt->close_on_exec->fds_bits[j] = 0;
1037                 spin_unlock(&files->file_lock);
1038                 for ( ; set ; i++,set >>= 1) {
1039                         if (set & 1) {
1040                                 sys_close(i);
1041                         }
1042                 }
1043                 spin_lock(&files->file_lock);
1044
1045         }
1046         spin_unlock(&files->file_lock);
1047 }
1048
1049 char *get_task_comm(char *buf, struct task_struct *tsk)
1050 {
1051         /* buf must be at least sizeof(tsk->comm) in size */
1052         task_lock(tsk);
1053         strncpy(buf, tsk->comm, sizeof(tsk->comm));
1054         task_unlock(tsk);
1055         return buf;
1056 }
1057 EXPORT_SYMBOL_GPL(get_task_comm);
1058
1059 void set_task_comm(struct task_struct *tsk, char *buf)
1060 {
1061         task_lock(tsk);
1062
1063         /*
1064          * Threads may access current->comm without holding
1065          * the task lock, so write the string carefully.
1066          * Readers without a lock may see incomplete new
1067          * names but are safe from non-terminating string reads.
1068          */
1069         memset(tsk->comm, 0, TASK_COMM_LEN);
1070         wmb();
1071         strlcpy(tsk->comm, buf, sizeof(tsk->comm));
1072         task_unlock(tsk);
1073         perf_event_comm(tsk);
1074 }
1075
1076 int flush_old_exec(struct linux_binprm * bprm)
1077 {
1078         int retval;
1079
1080         /*
1081          * Make sure we have a private signal table and that
1082          * we are unassociated from the previous thread group.
1083          */
1084         retval = de_thread(current);
1085         if (retval)
1086                 goto out;
1087
1088         set_mm_exe_file(bprm->mm, bprm->file);
1089
1090         /*
1091          * Release all of the old mmap stuff
1092          */
1093         acct_arg_size(bprm, 0);
1094         retval = exec_mmap(bprm->mm);
1095         if (retval)
1096                 goto out;
1097
1098         bprm->mm = NULL;                /* We're using it now */
1099
1100         set_fs(USER_DS);
1101         current->flags &=
1102                 ~(PF_RANDOMIZE | PF_KTHREAD | PF_NOFREEZE | PF_FREEZER_NOSIG);
1103         flush_thread();
1104         current->personality &= ~bprm->per_clear;
1105
1106         return 0;
1107
1108 out:
1109         return retval;
1110 }
1111 EXPORT_SYMBOL(flush_old_exec);
1112
1113 void would_dump(struct linux_binprm *bprm, struct file *file)
1114 {
1115         if (inode_permission(file->f_path.dentry->d_inode, MAY_READ) < 0)
1116                 bprm->interp_flags |= BINPRM_FLAGS_ENFORCE_NONDUMP;
1117 }
1118 EXPORT_SYMBOL(would_dump);
1119
1120 void setup_new_exec(struct linux_binprm * bprm)
1121 {
1122         int i, ch;
1123         const char *name;
1124         char tcomm[sizeof(current->comm)];
1125
1126         arch_pick_mmap_layout(current->mm);
1127
1128         /* This is the point of no return */
1129         current->sas_ss_sp = current->sas_ss_size = 0;
1130
1131         if (current_euid() == current_uid() && current_egid() == current_gid())
1132                 set_dumpable(current->mm, 1);
1133         else
1134                 set_dumpable(current->mm, suid_dumpable);
1135
1136         name = bprm->filename;
1137
1138         /* Copies the binary name from after last slash */
1139         for (i=0; (ch = *(name++)) != '\0';) {
1140                 if (ch == '/')
1141                         i = 0; /* overwrite what we wrote */
1142                 else
1143                         if (i < (sizeof(tcomm) - 1))
1144                                 tcomm[i++] = ch;
1145         }
1146         tcomm[i] = '\0';
1147         set_task_comm(current, tcomm);
1148
1149         /* Set the new mm task size. We have to do that late because it may
1150          * depend on TIF_32BIT which is only updated in flush_thread() on
1151          * some architectures like powerpc
1152          */
1153         current->mm->task_size = TASK_SIZE;
1154
1155         /* install the new credentials */
1156         if (bprm->cred->uid != current_euid() ||
1157             bprm->cred->gid != current_egid()) {
1158                 current->pdeath_signal = 0;
1159         } else {
1160                 would_dump(bprm, bprm->file);
1161                 if (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP)
1162                         set_dumpable(current->mm, suid_dumpable);
1163         }
1164
1165         /* An exec changes our domain. We are no longer part of the thread
1166            group */
1167
1168         current->self_exec_id++;
1169                         
1170         flush_signal_handlers(current, 0);
1171         flush_old_files(current->files);
1172 }
1173 EXPORT_SYMBOL(setup_new_exec);
1174
1175 /*
1176  * Prepare credentials and lock ->cred_guard_mutex.
1177  * install_exec_creds() commits the new creds and drops the lock.
1178  * Or, if exec fails before, free_bprm() should release ->cred and
1179  * and unlock.
1180  */
1181 int prepare_bprm_creds(struct linux_binprm *bprm)
1182 {
1183         if (mutex_lock_interruptible(&current->signal->cred_guard_mutex))
1184                 return -ERESTARTNOINTR;
1185
1186         bprm->cred = prepare_exec_creds();
1187         if (likely(bprm->cred))
1188                 return 0;
1189
1190         mutex_unlock(&current->signal->cred_guard_mutex);
1191         return -ENOMEM;
1192 }
1193
1194 void free_bprm(struct linux_binprm *bprm)
1195 {
1196         free_arg_pages(bprm);
1197         if (bprm->cred) {
1198                 mutex_unlock(&current->signal->cred_guard_mutex);
1199                 abort_creds(bprm->cred);
1200         }
1201         /* If a binfmt changed the interp, free it. */
1202         if (bprm->interp != bprm->filename)
1203                 kfree(bprm->interp);
1204         kfree(bprm);
1205 }
1206
1207 int bprm_change_interp(char *interp, struct linux_binprm *bprm)
1208 {
1209         /* If a binfmt changed the interp, free it first. */
1210         if (bprm->interp != bprm->filename)
1211                 kfree(bprm->interp);
1212         bprm->interp = kstrdup(interp, GFP_KERNEL);
1213         if (!bprm->interp)
1214                 return -ENOMEM;
1215         return 0;
1216 }
1217 EXPORT_SYMBOL(bprm_change_interp);
1218
1219 /*
1220  * install the new credentials for this executable
1221  */
1222 void install_exec_creds(struct linux_binprm *bprm)
1223 {
1224         security_bprm_committing_creds(bprm);
1225
1226         commit_creds(bprm->cred);
1227         bprm->cred = NULL;
1228
1229         /*
1230          * Disable monitoring for regular users
1231          * when executing setuid binaries. Must
1232          * wait until new credentials are committed
1233          * by commit_creds() above
1234          */
1235         if (get_dumpable(current->mm) != SUID_DUMP_USER)
1236                 perf_event_exit_task(current);
1237         /*
1238          * cred_guard_mutex must be held at least to this point to prevent
1239          * ptrace_attach() from altering our determination of the task's
1240          * credentials; any time after this it may be unlocked.
1241          */
1242         security_bprm_committed_creds(bprm);
1243         mutex_unlock(&current->signal->cred_guard_mutex);
1244 }
1245 EXPORT_SYMBOL(install_exec_creds);
1246
1247 /*
1248  * determine how safe it is to execute the proposed program
1249  * - the caller must hold ->cred_guard_mutex to protect against
1250  *   PTRACE_ATTACH
1251  */
1252 int check_unsafe_exec(struct linux_binprm *bprm)
1253 {
1254         struct task_struct *p = current, *t;
1255         unsigned n_fs;
1256         int res = 0;
1257
1258         if (p->ptrace) {
1259                 if (p->ptrace & PT_PTRACE_CAP)
1260                         bprm->unsafe |= LSM_UNSAFE_PTRACE_CAP;
1261                 else
1262                         bprm->unsafe |= LSM_UNSAFE_PTRACE;
1263         }
1264
1265         n_fs = 1;
1266         spin_lock(&p->fs->lock);
1267         rcu_read_lock();
1268         for (t = next_thread(p); t != p; t = next_thread(t)) {
1269                 if (t->fs == p->fs)
1270                         n_fs++;
1271         }
1272         rcu_read_unlock();
1273
1274         if (p->fs->users > n_fs) {
1275                 bprm->unsafe |= LSM_UNSAFE_SHARE;
1276         } else {
1277                 res = -EAGAIN;
1278                 if (!p->fs->in_exec) {
1279                         p->fs->in_exec = 1;
1280                         res = 1;
1281                 }
1282         }
1283         spin_unlock(&p->fs->lock);
1284
1285         return res;
1286 }
1287
1288 static void bprm_fill_uid(struct linux_binprm *bprm)
1289 {
1290         struct inode *inode;
1291         unsigned int mode;
1292         uid_t uid;
1293         gid_t gid;
1294
1295         /* clear any previous set[ug]id data from a previous binary */
1296         bprm->cred->euid = current_euid();
1297         bprm->cred->egid = current_egid();
1298
1299         if (bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID)
1300                 return;
1301
1302         inode = bprm->file->f_path.dentry->d_inode;
1303         mode = ACCESS_ONCE(inode->i_mode);
1304         if (!(mode & (S_ISUID|S_ISGID)))
1305                 return;
1306
1307         /* Be careful if suid/sgid is set */
1308         mutex_lock(&inode->i_mutex);
1309
1310         /* reload atomically mode/uid/gid now that lock held */
1311         mode = inode->i_mode;
1312         uid = inode->i_uid;
1313         gid = inode->i_gid;
1314         mutex_unlock(&inode->i_mutex);
1315
1316         if (mode & S_ISUID) {
1317                 bprm->per_clear |= PER_CLEAR_ON_SETID;
1318                 bprm->cred->euid = uid;
1319         }
1320
1321         if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
1322                 bprm->per_clear |= PER_CLEAR_ON_SETID;
1323                 bprm->cred->egid = gid;
1324         }
1325 }
1326
1327 /* 
1328  * Fill the binprm structure from the inode. 
1329  * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
1330  *
1331  * This may be called multiple times for binary chains (scripts for example).
1332  */
1333 int prepare_binprm(struct linux_binprm *bprm)
1334 {
1335         int retval;
1336
1337         if (bprm->file->f_op == NULL)
1338                 return -EACCES;
1339
1340         bprm_fill_uid(bprm);
1341
1342         /* fill in binprm security blob */
1343         retval = security_bprm_set_creds(bprm);
1344         if (retval)
1345                 return retval;
1346         bprm->cred_prepared = 1;
1347
1348         memset(bprm->buf, 0, BINPRM_BUF_SIZE);
1349         return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
1350 }
1351
1352 EXPORT_SYMBOL(prepare_binprm);
1353
1354 /*
1355  * Arguments are '\0' separated strings found at the location bprm->p
1356  * points to; chop off the first by relocating brpm->p to right after
1357  * the first '\0' encountered.
1358  */
1359 int remove_arg_zero(struct linux_binprm *bprm)
1360 {
1361         int ret = 0;
1362         unsigned long offset;
1363         char *kaddr;
1364         struct page *page;
1365
1366         if (!bprm->argc)
1367                 return 0;
1368
1369         do {
1370                 offset = bprm->p & ~PAGE_MASK;
1371                 page = get_arg_page(bprm, bprm->p, 0);
1372                 if (!page) {
1373                         ret = -EFAULT;
1374                         goto out;
1375                 }
1376                 kaddr = kmap_atomic(page, KM_USER0);
1377
1378                 for (; offset < PAGE_SIZE && kaddr[offset];
1379                                 offset++, bprm->p++)
1380                         ;
1381
1382                 kunmap_atomic(kaddr, KM_USER0);
1383                 put_arg_page(page);
1384
1385                 if (offset == PAGE_SIZE)
1386                         free_arg_page(bprm, (bprm->p >> PAGE_SHIFT) - 1);
1387         } while (offset == PAGE_SIZE);
1388
1389         bprm->p++;
1390         bprm->argc--;
1391         ret = 0;
1392
1393 out:
1394         return ret;
1395 }
1396 EXPORT_SYMBOL(remove_arg_zero);
1397
1398 /*
1399  * cycle the list of binary formats handler, until one recognizes the image
1400  */
1401 int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs)
1402 {
1403         unsigned int depth = bprm->recursion_depth;
1404         int try,retval;
1405         struct linux_binfmt *fmt;
1406         pid_t old_pid;
1407
1408         /* This allows 4 levels of binfmt rewrites before failing hard. */
1409         if (depth > 5)
1410                 return -ELOOP;
1411
1412         retval = security_bprm_check(bprm);
1413         if (retval)
1414                 return retval;
1415
1416         retval = audit_bprm(bprm);
1417         if (retval)
1418                 return retval;
1419
1420         /* Need to fetch pid before load_binary changes it */
1421         rcu_read_lock();
1422         old_pid = task_pid_nr_ns(current, task_active_pid_ns(current->parent));
1423         rcu_read_unlock();
1424
1425         retval = -ENOENT;
1426         for (try=0; try<2; try++) {
1427                 read_lock(&binfmt_lock);
1428                 list_for_each_entry(fmt, &formats, lh) {
1429                         int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
1430                         if (!fn)
1431                                 continue;
1432                         if (!try_module_get(fmt->module))
1433                                 continue;
1434                         read_unlock(&binfmt_lock);
1435                         bprm->recursion_depth = depth + 1;
1436                         retval = fn(bprm, regs);
1437                         bprm->recursion_depth = depth;
1438                         if (retval >= 0) {
1439                                 if (depth == 0)
1440                                         ptrace_event(PTRACE_EVENT_EXEC,
1441                                                         old_pid);
1442                                 put_binfmt(fmt);
1443                                 allow_write_access(bprm->file);
1444                                 if (bprm->file)
1445                                         fput(bprm->file);
1446                                 bprm->file = NULL;
1447                                 current->did_exec = 1;
1448                                 proc_exec_connector(current);
1449                                 return retval;
1450                         }
1451                         read_lock(&binfmt_lock);
1452                         put_binfmt(fmt);
1453                         if (retval != -ENOEXEC || bprm->mm == NULL)
1454                                 break;
1455                         if (!bprm->file) {
1456                                 read_unlock(&binfmt_lock);
1457                                 return retval;
1458                         }
1459                 }
1460                 read_unlock(&binfmt_lock);
1461 #ifdef CONFIG_MODULES
1462                 if (retval != -ENOEXEC || bprm->mm == NULL) {
1463                         break;
1464                 } else {
1465 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
1466                         if (printable(bprm->buf[0]) &&
1467                             printable(bprm->buf[1]) &&
1468                             printable(bprm->buf[2]) &&
1469                             printable(bprm->buf[3]))
1470                                 break; /* -ENOEXEC */
1471                         if (try)
1472                                 break; /* -ENOEXEC */
1473                         request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
1474                 }
1475 #else
1476                 break;
1477 #endif
1478         }
1479         return retval;
1480 }
1481
1482 EXPORT_SYMBOL(search_binary_handler);
1483
1484 /*
1485  * sys_execve() executes a new program.
1486  */
1487 static int do_execve_common(const char *filename,
1488                                 struct user_arg_ptr argv,
1489                                 struct user_arg_ptr envp,
1490                                 struct pt_regs *regs)
1491 {
1492         struct linux_binprm *bprm;
1493         struct file *file;
1494         struct files_struct *displaced;
1495         bool clear_in_exec;
1496         int retval;
1497         const struct cred *cred = current_cred();
1498
1499         /*
1500          * We move the actual failure in case of RLIMIT_NPROC excess from
1501          * set*uid() to execve() because too many poorly written programs
1502          * don't check setuid() return code.  Here we additionally recheck
1503          * whether NPROC limit is still exceeded.
1504          */
1505         if ((current->flags & PF_NPROC_EXCEEDED) &&
1506             atomic_read(&cred->user->processes) > rlimit(RLIMIT_NPROC)) {
1507                 retval = -EAGAIN;
1508                 goto out_ret;
1509         }
1510
1511         /* We're below the limit (still or again), so we don't want to make
1512          * further execve() calls fail. */
1513         current->flags &= ~PF_NPROC_EXCEEDED;
1514
1515         retval = unshare_files(&displaced);
1516         if (retval)
1517                 goto out_ret;
1518
1519         retval = -ENOMEM;
1520         bprm = kzalloc(sizeof(*bprm), GFP_KERNEL);
1521         if (!bprm)
1522                 goto out_files;
1523
1524         retval = prepare_bprm_creds(bprm);
1525         if (retval)
1526                 goto out_free;
1527
1528         retval = check_unsafe_exec(bprm);
1529         if (retval < 0)
1530                 goto out_free;
1531         clear_in_exec = retval;
1532         current->in_execve = 1;
1533
1534         file = open_exec(filename);
1535         retval = PTR_ERR(file);
1536         if (IS_ERR(file))
1537                 goto out_unmark;
1538
1539         sched_exec();
1540
1541         bprm->file = file;
1542         bprm->filename = filename;
1543         bprm->interp = filename;
1544
1545         retval = bprm_mm_init(bprm);
1546         if (retval)
1547                 goto out_file;
1548
1549         bprm->argc = count(argv, MAX_ARG_STRINGS);
1550         if ((retval = bprm->argc) < 0)
1551                 goto out;
1552
1553         bprm->envc = count(envp, MAX_ARG_STRINGS);
1554         if ((retval = bprm->envc) < 0)
1555                 goto out;
1556
1557         retval = prepare_binprm(bprm);
1558         if (retval < 0)
1559                 goto out;
1560
1561         retval = copy_strings_kernel(1, &bprm->filename, bprm);
1562         if (retval < 0)
1563                 goto out;
1564
1565         bprm->exec = bprm->p;
1566         retval = copy_strings(bprm->envc, envp, bprm);
1567         if (retval < 0)
1568                 goto out;
1569
1570         retval = copy_strings(bprm->argc, argv, bprm);
1571         if (retval < 0)
1572                 goto out;
1573
1574         retval = search_binary_handler(bprm,regs);
1575         if (retval < 0)
1576                 goto out;
1577
1578         /* execve succeeded */
1579         current->fs->in_exec = 0;
1580         current->in_execve = 0;
1581         acct_update_integrals(current);
1582         free_bprm(bprm);
1583         if (displaced)
1584                 put_files_struct(displaced);
1585         return retval;
1586
1587 out:
1588         if (bprm->mm) {
1589                 acct_arg_size(bprm, 0);
1590                 mmput(bprm->mm);
1591         }
1592
1593 out_file:
1594         if (bprm->file) {
1595                 allow_write_access(bprm->file);
1596                 fput(bprm->file);
1597         }
1598
1599 out_unmark:
1600         if (clear_in_exec)
1601                 current->fs->in_exec = 0;
1602         current->in_execve = 0;
1603
1604 out_free:
1605         free_bprm(bprm);
1606
1607 out_files:
1608         if (displaced)
1609                 reset_files_struct(displaced);
1610 out_ret:
1611         return retval;
1612 }
1613
1614 int do_execve(const char *filename,
1615         const char __user *const __user *__argv,
1616         const char __user *const __user *__envp,
1617         struct pt_regs *regs)
1618 {
1619         struct user_arg_ptr argv = { .ptr.native = __argv };
1620         struct user_arg_ptr envp = { .ptr.native = __envp };
1621         return do_execve_common(filename, argv, envp, regs);
1622 }
1623
1624 #ifdef CONFIG_COMPAT
1625 int compat_do_execve(char *filename,
1626         compat_uptr_t __user *__argv,
1627         compat_uptr_t __user *__envp,
1628         struct pt_regs *regs)
1629 {
1630         struct user_arg_ptr argv = {
1631                 .is_compat = true,
1632                 .ptr.compat = __argv,
1633         };
1634         struct user_arg_ptr envp = {
1635                 .is_compat = true,
1636                 .ptr.compat = __envp,
1637         };
1638         return do_execve_common(filename, argv, envp, regs);
1639 }
1640 #endif
1641
1642 void set_binfmt(struct linux_binfmt *new)
1643 {
1644         struct mm_struct *mm = current->mm;
1645
1646         if (mm->binfmt)
1647                 module_put(mm->binfmt->module);
1648
1649         mm->binfmt = new;
1650         if (new)
1651                 __module_get(new->module);
1652 }
1653
1654 EXPORT_SYMBOL(set_binfmt);
1655
1656 static int expand_corename(struct core_name *cn)
1657 {
1658         char *old_corename = cn->corename;
1659
1660         cn->size = CORENAME_MAX_SIZE * atomic_inc_return(&call_count);
1661         cn->corename = krealloc(old_corename, cn->size, GFP_KERNEL);
1662
1663         if (!cn->corename) {
1664                 kfree(old_corename);
1665                 return -ENOMEM;
1666         }
1667
1668         return 0;
1669 }
1670
1671 static int cn_printf(struct core_name *cn, const char *fmt, ...)
1672 {
1673         char *cur;
1674         int need;
1675         int ret;
1676         va_list arg;
1677
1678         va_start(arg, fmt);
1679         need = vsnprintf(NULL, 0, fmt, arg);
1680         va_end(arg);
1681
1682         if (likely(need < cn->size - cn->used - 1))
1683                 goto out_printf;
1684
1685         ret = expand_corename(cn);
1686         if (ret)
1687                 goto expand_fail;
1688
1689 out_printf:
1690         cur = cn->corename + cn->used;
1691         va_start(arg, fmt);
1692         vsnprintf(cur, need + 1, fmt, arg);
1693         va_end(arg);
1694         cn->used += need;
1695         return 0;
1696
1697 expand_fail:
1698         return ret;
1699 }
1700
1701 static void cn_escape(char *str)
1702 {
1703         for (; *str; str++)
1704                 if (*str == '/')
1705                         *str = '!';
1706 }
1707
1708 static int cn_print_exe_file(struct core_name *cn)
1709 {
1710         struct file *exe_file;
1711         char *pathbuf, *path;
1712         int ret;
1713
1714         exe_file = get_mm_exe_file(current->mm);
1715         if (!exe_file) {
1716                 char *commstart = cn->corename + cn->used;
1717                 ret = cn_printf(cn, "%s (path unknown)", current->comm);
1718                 cn_escape(commstart);
1719                 return ret;
1720         }
1721
1722         pathbuf = kmalloc(PATH_MAX, GFP_TEMPORARY);
1723         if (!pathbuf) {
1724                 ret = -ENOMEM;
1725                 goto put_exe_file;
1726         }
1727
1728         path = d_path(&exe_file->f_path, pathbuf, PATH_MAX);
1729         if (IS_ERR(path)) {
1730                 ret = PTR_ERR(path);
1731                 goto free_buf;
1732         }
1733
1734         cn_escape(path);
1735
1736         ret = cn_printf(cn, "%s", path);
1737
1738 free_buf:
1739         kfree(pathbuf);
1740 put_exe_file:
1741         fput(exe_file);
1742         return ret;
1743 }
1744
1745 /* format_corename will inspect the pattern parameter, and output a
1746  * name into corename, which must have space for at least
1747  * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
1748  */
1749 static int format_corename(struct core_name *cn, long signr)
1750 {
1751         const struct cred *cred = current_cred();
1752         const char *pat_ptr = core_pattern;
1753         int ispipe = (*pat_ptr == '|');
1754         int pid_in_pattern = 0;
1755         int err = 0;
1756
1757         cn->size = CORENAME_MAX_SIZE * atomic_read(&call_count);
1758         cn->corename = kmalloc(cn->size, GFP_KERNEL);
1759         cn->used = 0;
1760
1761         if (!cn->corename)
1762                 return -ENOMEM;
1763
1764         /* Repeat as long as we have more pattern to process and more output
1765            space */
1766         while (*pat_ptr) {
1767                 if (*pat_ptr != '%') {
1768                         if (*pat_ptr == 0)
1769                                 goto out;
1770                         err = cn_printf(cn, "%c", *pat_ptr++);
1771                 } else {
1772                         switch (*++pat_ptr) {
1773                         /* single % at the end, drop that */
1774                         case 0:
1775                                 goto out;
1776                         /* Double percent, output one percent */
1777                         case '%':
1778                                 err = cn_printf(cn, "%c", '%');
1779                                 break;
1780                         /* pid */
1781                         case 'p':
1782                                 pid_in_pattern = 1;
1783                                 err = cn_printf(cn, "%d",
1784                                               task_tgid_vnr(current));
1785                                 break;
1786                         /* uid */
1787                         case 'u':
1788                                 err = cn_printf(cn, "%d", cred->uid);
1789                                 break;
1790                         /* gid */
1791                         case 'g':
1792                                 err = cn_printf(cn, "%d", cred->gid);
1793                                 break;
1794                         /* signal that caused the coredump */
1795                         case 's':
1796                                 err = cn_printf(cn, "%ld", signr);
1797                                 break;
1798                         /* UNIX time of coredump */
1799                         case 't': {
1800                                 struct timeval tv;
1801                                 do_gettimeofday(&tv);
1802                                 err = cn_printf(cn, "%lu", tv.tv_sec);
1803                                 break;
1804                         }
1805                         /* hostname */
1806                         case 'h': {
1807                                 char *namestart = cn->corename + cn->used;
1808                                 down_read(&uts_sem);
1809                                 err = cn_printf(cn, "%s",
1810                                               utsname()->nodename);
1811                                 up_read(&uts_sem);
1812                                 cn_escape(namestart);
1813                                 break;
1814                         }
1815                         /* executable */
1816                         case 'e': {
1817                                 char *commstart = cn->corename + cn->used;
1818                                 err = cn_printf(cn, "%s", current->comm);
1819                                 cn_escape(commstart);
1820                                 break;
1821                         }
1822                         case 'E':
1823                                 err = cn_print_exe_file(cn);
1824                                 break;
1825                         /* core limit size */
1826                         case 'c':
1827                                 err = cn_printf(cn, "%lu",
1828                                               rlimit(RLIMIT_CORE));
1829                                 break;
1830                         default:
1831                                 break;
1832                         }
1833                         ++pat_ptr;
1834                 }
1835
1836                 if (err)
1837                         return err;
1838         }
1839
1840         /* Backward compatibility with core_uses_pid:
1841          *
1842          * If core_pattern does not include a %p (as is the default)
1843          * and core_uses_pid is set, then .%pid will be appended to
1844          * the filename. Do not do this for piped commands. */
1845         if (!ispipe && !pid_in_pattern && core_uses_pid) {
1846                 err = cn_printf(cn, ".%d", task_tgid_vnr(current));
1847                 if (err)
1848                         return err;
1849         }
1850 out:
1851         return ispipe;
1852 }
1853
1854 static int zap_process(struct task_struct *start, int exit_code)
1855 {
1856         struct task_struct *t;
1857         int nr = 0;
1858
1859         start->signal->flags = SIGNAL_GROUP_EXIT;
1860         start->signal->group_exit_code = exit_code;
1861         start->signal->group_stop_count = 0;
1862
1863         t = start;
1864         do {
1865                 task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
1866                 if (t != current && t->mm) {
1867                         sigaddset(&t->pending.signal, SIGKILL);
1868                         signal_wake_up(t, 1);
1869                         nr++;
1870                 }
1871         } while_each_thread(start, t);
1872
1873         return nr;
1874 }
1875
1876 static inline int zap_threads(struct task_struct *tsk, struct mm_struct *mm,
1877                                 struct core_state *core_state, int exit_code)
1878 {
1879         struct task_struct *g, *p;
1880         unsigned long flags;
1881         int nr = -EAGAIN;
1882
1883         spin_lock_irq(&tsk->sighand->siglock);
1884         if (!signal_group_exit(tsk->signal)) {
1885                 mm->core_state = core_state;
1886                 nr = zap_process(tsk, exit_code);
1887         }
1888         spin_unlock_irq(&tsk->sighand->siglock);
1889         if (unlikely(nr < 0))
1890                 return nr;
1891
1892         if (atomic_read(&mm->mm_users) == nr + 1)
1893                 goto done;
1894         /*
1895          * We should find and kill all tasks which use this mm, and we should
1896          * count them correctly into ->nr_threads. We don't take tasklist
1897          * lock, but this is safe wrt:
1898          *
1899          * fork:
1900          *      None of sub-threads can fork after zap_process(leader). All
1901          *      processes which were created before this point should be
1902          *      visible to zap_threads() because copy_process() adds the new
1903          *      process to the tail of init_task.tasks list, and lock/unlock
1904          *      of ->siglock provides a memory barrier.
1905          *
1906          * do_exit:
1907          *      The caller holds mm->mmap_sem. This means that the task which
1908          *      uses this mm can't pass exit_mm(), so it can't exit or clear
1909          *      its ->mm.
1910          *
1911          * de_thread:
1912          *      It does list_replace_rcu(&leader->tasks, &current->tasks),
1913          *      we must see either old or new leader, this does not matter.
1914          *      However, it can change p->sighand, so lock_task_sighand(p)
1915          *      must be used. Since p->mm != NULL and we hold ->mmap_sem
1916          *      it can't fail.
1917          *
1918          *      Note also that "g" can be the old leader with ->mm == NULL
1919          *      and already unhashed and thus removed from ->thread_group.
1920          *      This is OK, __unhash_process()->list_del_rcu() does not
1921          *      clear the ->next pointer, we will find the new leader via
1922          *      next_thread().
1923          */
1924         rcu_read_lock();
1925         for_each_process(g) {
1926                 if (g == tsk->group_leader)
1927                         continue;
1928                 if (g->flags & PF_KTHREAD)
1929                         continue;
1930                 p = g;
1931                 do {
1932                         if (p->mm) {
1933                                 if (unlikely(p->mm == mm)) {
1934                                         lock_task_sighand(p, &flags);
1935                                         nr += zap_process(p, exit_code);
1936                                         unlock_task_sighand(p, &flags);
1937                                 }
1938                                 break;
1939                         }
1940                 } while_each_thread(g, p);
1941         }
1942         rcu_read_unlock();
1943 done:
1944         atomic_set(&core_state->nr_threads, nr);
1945         return nr;
1946 }
1947
1948 static int coredump_wait(int exit_code, struct core_state *core_state)
1949 {
1950         struct task_struct *tsk = current;
1951         struct mm_struct *mm = tsk->mm;
1952         struct completion *vfork_done;
1953         int core_waiters = -EBUSY;
1954
1955         init_completion(&core_state->startup);
1956         core_state->dumper.task = tsk;
1957         core_state->dumper.next = NULL;
1958
1959         down_write(&mm->mmap_sem);
1960         if (!mm->core_state)
1961                 core_waiters = zap_threads(tsk, mm, core_state, exit_code);
1962         up_write(&mm->mmap_sem);
1963
1964         if (unlikely(core_waiters < 0))
1965                 goto fail;
1966
1967         /*
1968          * Make sure nobody is waiting for us to release the VM,
1969          * otherwise we can deadlock when we wait on each other
1970          */
1971         vfork_done = tsk->vfork_done;
1972         if (vfork_done) {
1973                 tsk->vfork_done = NULL;
1974                 complete(vfork_done);
1975         }
1976
1977         if (core_waiters)
1978                 wait_for_completion(&core_state->startup);
1979 fail:
1980         return core_waiters;
1981 }
1982
1983 static void coredump_finish(struct mm_struct *mm)
1984 {
1985         struct core_thread *curr, *next;
1986         struct task_struct *task;
1987
1988         next = mm->core_state->dumper.next;
1989         while ((curr = next) != NULL) {
1990                 next = curr->next;
1991                 task = curr->task;
1992                 /*
1993                  * see exit_mm(), curr->task must not see
1994                  * ->task == NULL before we read ->next.
1995                  */
1996                 smp_mb();
1997                 curr->task = NULL;
1998                 wake_up_process(task);
1999         }
2000
2001         mm->core_state = NULL;
2002 }
2003
2004 /*
2005  * set_dumpable converts traditional three-value dumpable to two flags and
2006  * stores them into mm->flags.  It modifies lower two bits of mm->flags, but
2007  * these bits are not changed atomically.  So get_dumpable can observe the
2008  * intermediate state.  To avoid doing unexpected behavior, get get_dumpable
2009  * return either old dumpable or new one by paying attention to the order of
2010  * modifying the bits.
2011  *
2012  * dumpable |   mm->flags (binary)
2013  * old  new | initial interim  final
2014  * ---------+-----------------------
2015  *  0    1  |   00      01      01
2016  *  0    2  |   00      10(*)   11
2017  *  1    0  |   01      00      00
2018  *  1    2  |   01      11      11
2019  *  2    0  |   11      10(*)   00
2020  *  2    1  |   11      11      01
2021  *
2022  * (*) get_dumpable regards interim value of 10 as 11.
2023  */
2024 void set_dumpable(struct mm_struct *mm, int value)
2025 {
2026         switch (value) {
2027         case 0:
2028                 clear_bit(MMF_DUMPABLE, &mm->flags);
2029                 smp_wmb();
2030                 clear_bit(MMF_DUMP_SECURELY, &mm->flags);
2031                 break;
2032         case 1:
2033                 set_bit(MMF_DUMPABLE, &mm->flags);
2034                 smp_wmb();
2035                 clear_bit(MMF_DUMP_SECURELY, &mm->flags);
2036                 break;
2037         case 2:
2038                 set_bit(MMF_DUMP_SECURELY, &mm->flags);
2039                 smp_wmb();
2040                 set_bit(MMF_DUMPABLE, &mm->flags);
2041                 break;
2042         }
2043 }
2044
2045 static int __get_dumpable(unsigned long mm_flags)
2046 {
2047         int ret;
2048
2049         ret = mm_flags & MMF_DUMPABLE_MASK;
2050         return (ret >= 2) ? 2 : ret;
2051 }
2052
2053 /*
2054  * This returns the actual value of the suid_dumpable flag. For things
2055  * that are using this for checking for privilege transitions, it must
2056  * test against SUID_DUMP_USER rather than treating it as a boolean
2057  * value.
2058  */
2059 int get_dumpable(struct mm_struct *mm)
2060 {
2061         return __get_dumpable(mm->flags);
2062 }
2063
2064 static void wait_for_dump_helpers(struct file *file)
2065 {
2066         struct pipe_inode_info *pipe;
2067
2068         pipe = file->f_path.dentry->d_inode->i_pipe;
2069
2070         pipe_lock(pipe);
2071         pipe->readers++;
2072         pipe->writers--;
2073
2074         while ((pipe->readers > 1) && (!signal_pending(current))) {
2075                 wake_up_interruptible_sync(&pipe->wait);
2076                 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
2077                 pipe_wait(pipe);
2078         }
2079
2080         pipe->readers--;
2081         pipe->writers++;
2082         pipe_unlock(pipe);
2083
2084 }
2085
2086
2087 /*
2088  * umh_pipe_setup
2089  * helper function to customize the process used
2090  * to collect the core in userspace.  Specifically
2091  * it sets up a pipe and installs it as fd 0 (stdin)
2092  * for the process.  Returns 0 on success, or
2093  * PTR_ERR on failure.
2094  * Note that it also sets the core limit to 1.  This
2095  * is a special value that we use to trap recursive
2096  * core dumps
2097  */
2098 static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
2099 {
2100         struct file *rp, *wp;
2101         struct fdtable *fdt;
2102         struct coredump_params *cp = (struct coredump_params *)info->data;
2103         struct files_struct *cf = current->files;
2104
2105         wp = create_write_pipe(0);
2106         if (IS_ERR(wp))
2107                 return PTR_ERR(wp);
2108
2109         rp = create_read_pipe(wp, 0);
2110         if (IS_ERR(rp)) {
2111                 free_write_pipe(wp);
2112                 return PTR_ERR(rp);
2113         }
2114
2115         cp->file = wp;
2116
2117         sys_close(0);
2118         fd_install(0, rp);
2119         spin_lock(&cf->file_lock);
2120         fdt = files_fdtable(cf);
2121         FD_SET(0, fdt->open_fds);
2122         FD_CLR(0, fdt->close_on_exec);
2123         spin_unlock(&cf->file_lock);
2124
2125         /* and disallow core files too */
2126         current->signal->rlim[RLIMIT_CORE] = (struct rlimit){1, 1};
2127
2128         return 0;
2129 }
2130
2131 void do_coredump(long signr, int exit_code, struct pt_regs *regs)
2132 {
2133         struct core_state core_state;
2134         struct core_name cn;
2135         struct mm_struct *mm = current->mm;
2136         struct linux_binfmt * binfmt;
2137         const struct cred *old_cred;
2138         struct cred *cred;
2139         int retval = 0;
2140         int ispipe;
2141         /* require nonrelative corefile path and be extra careful */
2142         bool need_suid_safe = false;
2143         static atomic_t core_dump_count = ATOMIC_INIT(0);
2144         struct coredump_params cprm = {
2145                 .signr = signr,
2146                 .regs = regs,
2147                 .limit = rlimit(RLIMIT_CORE),
2148                 /*
2149                  * We must use the same mm->flags while dumping core to avoid
2150                  * inconsistency of bit flags, since this flag is not protected
2151                  * by any locks.
2152                  */
2153                 .mm_flags = mm->flags,
2154         };
2155
2156         audit_core_dumps(signr);
2157
2158         binfmt = mm->binfmt;
2159         if (!binfmt || !binfmt->core_dump)
2160                 goto fail;
2161         if (!__get_dumpable(cprm.mm_flags))
2162                 goto fail;
2163
2164         cred = prepare_creds();
2165         if (!cred)
2166                 goto fail;
2167         /*
2168          * We cannot trust fsuid as being the "true" uid of the process
2169          * nor do we know its entire history. We only know it was tainted
2170          * so we dump it as root in mode 2, and only into a controlled
2171          * environment (pipe handler or fully qualified path).
2172          */
2173         if (__get_dumpable(cprm.mm_flags) == 2) {
2174                 /* Setuid core dump mode */
2175                 cred->fsuid = 0;        /* Dump root private */
2176                 need_suid_safe = true;
2177         }
2178
2179         retval = coredump_wait(exit_code, &core_state);
2180         if (retval < 0)
2181                 goto fail_creds;
2182
2183         old_cred = override_creds(cred);
2184
2185         /*
2186          * Clear any false indication of pending signals that might
2187          * be seen by the filesystem code called to write the core file.
2188          */
2189         clear_thread_flag(TIF_SIGPENDING);
2190
2191         ispipe = format_corename(&cn, signr);
2192
2193         if (ispipe) {
2194                 int dump_count;
2195                 char **helper_argv;
2196
2197                 if (ispipe < 0) {
2198                         printk(KERN_WARNING "format_corename failed\n");
2199                         printk(KERN_WARNING "Aborting core\n");
2200                         goto fail_corename;
2201                 }
2202
2203                 if (cprm.limit == 1) {
2204                         /*
2205                          * Normally core limits are irrelevant to pipes, since
2206                          * we're not writing to the file system, but we use
2207                          * cprm.limit of 1 here as a speacial value. Any
2208                          * non-1 limit gets set to RLIM_INFINITY below, but
2209                          * a limit of 0 skips the dump.  This is a consistent
2210                          * way to catch recursive crashes.  We can still crash
2211                          * if the core_pattern binary sets RLIM_CORE =  !1
2212                          * but it runs as root, and can do lots of stupid things
2213                          * Note that we use task_tgid_vnr here to grab the pid
2214                          * of the process group leader.  That way we get the
2215                          * right pid if a thread in a multi-threaded
2216                          * core_pattern process dies.
2217                          */
2218                         printk(KERN_WARNING
2219                                 "Process %d(%s) has RLIMIT_CORE set to 1\n",
2220                                 task_tgid_vnr(current), current->comm);
2221                         printk(KERN_WARNING "Aborting core\n");
2222                         goto fail_unlock;
2223                 }
2224                 cprm.limit = RLIM_INFINITY;
2225
2226                 dump_count = atomic_inc_return(&core_dump_count);
2227                 if (core_pipe_limit && (core_pipe_limit < dump_count)) {
2228                         printk(KERN_WARNING "Pid %d(%s) over core_pipe_limit\n",
2229                                task_tgid_vnr(current), current->comm);
2230                         printk(KERN_WARNING "Skipping core dump\n");
2231                         goto fail_dropcount;
2232                 }
2233
2234                 helper_argv = argv_split(GFP_KERNEL, cn.corename+1, NULL);
2235                 if (!helper_argv) {
2236                         printk(KERN_WARNING "%s failed to allocate memory\n",
2237                                __func__);
2238                         goto fail_dropcount;
2239                 }
2240
2241                 retval = call_usermodehelper_fns(helper_argv[0], helper_argv,
2242                                         NULL, UMH_WAIT_EXEC, umh_pipe_setup,
2243                                         NULL, &cprm);
2244                 argv_free(helper_argv);
2245                 if (retval) {
2246                         printk(KERN_INFO "Core dump to %s pipe failed\n",
2247                                cn.corename);
2248                         goto close_fail;
2249                 }
2250         } else {
2251                 struct inode *inode;
2252                 int open_flags = O_CREAT | O_RDWR | O_NOFOLLOW |
2253                                  O_LARGEFILE | O_EXCL;
2254
2255                 if (cprm.limit < binfmt->min_coredump)
2256                         goto fail_unlock;
2257
2258                 if (need_suid_safe && cn.corename[0] != '/') {
2259                         printk(KERN_WARNING "Pid %d(%s) can only dump core "\
2260                                 "to fully qualified path!\n",
2261                                 task_tgid_vnr(current), current->comm);
2262                         printk(KERN_WARNING "Skipping core dump\n");
2263                         goto fail_unlock;
2264                 }
2265
2266                 /*
2267                  * Unlink the file if it exists unless this is a SUID
2268                  * binary - in that case, we're running around with root
2269                  * privs and don't want to unlink another user's coredump.
2270                  */
2271                 if (!need_suid_safe) {
2272                         mm_segment_t old_fs;
2273
2274                         old_fs = get_fs();
2275                         set_fs(KERNEL_DS);
2276                         /*
2277                          * If it doesn't exist, that's fine. If there's some
2278                          * other problem, we'll catch it at the filp_open().
2279                          */
2280                         (void) sys_unlink((const char __user *)cn.corename);
2281                         set_fs(old_fs);
2282                 }
2283
2284                 /*
2285                  * There is a race between unlinking and creating the
2286                  * file, but if that causes an EEXIST here, that's
2287                  * fine - another process raced with us while creating
2288                  * the corefile, and the other process won. To userspace,
2289                  * what matters is that at least one of the two processes
2290                  * writes its coredump successfully, not which one.
2291                  */
2292                 if (need_suid_safe) {
2293                         /*
2294                          * Using user namespaces, normal user tasks can change
2295                          * their current->fs->root to point to arbitrary
2296                          * directories. Since the intention of the "only dump
2297                          * with a fully qualified path" rule is to control where
2298                          * coredumps may be placed using root privileges,
2299                          * current->fs->root must not be used. Instead, use the
2300                          * root directory of init_task.
2301                          */
2302                         struct path root;
2303
2304                         task_lock(&init_task);
2305                         get_fs_root(init_task.fs, &root);
2306                         task_unlock(&init_task);
2307                         cprm.file = file_open_root(root.dentry, root.mnt,
2308                                 cn.corename, open_flags, 0600);
2309                         path_put(&root);
2310                 } else {
2311                         cprm.file = filp_open(cn.corename, open_flags, 0600);
2312                 }
2313                 if (IS_ERR(cprm.file))
2314                         goto fail_unlock;
2315
2316                 inode = cprm.file->f_path.dentry->d_inode;
2317                 if (inode->i_nlink > 1)
2318                         goto close_fail;
2319                 if (d_unhashed(cprm.file->f_path.dentry))
2320                         goto close_fail;
2321                 /*
2322                  * AK: actually i see no reason to not allow this for named
2323                  * pipes etc, but keep the previous behaviour for now.
2324                  */
2325                 if (!S_ISREG(inode->i_mode))
2326                         goto close_fail;
2327                 /*
2328                  * Dont allow local users get cute and trick others to coredump
2329                  * into their pre-created files.
2330                  */
2331                 if (inode->i_uid != current_fsuid())
2332                         goto close_fail;
2333                 if (!cprm.file->f_op || !cprm.file->f_op->write)
2334                         goto close_fail;
2335                 if (do_truncate(cprm.file->f_path.dentry, 0, 0, cprm.file))
2336                         goto close_fail;
2337         }
2338
2339         retval = binfmt->core_dump(&cprm);
2340         if (retval)
2341                 current->signal->group_exit_code |= 0x80;
2342
2343         if (ispipe && core_pipe_limit)
2344                 wait_for_dump_helpers(cprm.file);
2345 close_fail:
2346         if (cprm.file)
2347                 filp_close(cprm.file, NULL);
2348 fail_dropcount:
2349         if (ispipe)
2350                 atomic_dec(&core_dump_count);
2351 fail_unlock:
2352         kfree(cn.corename);
2353 fail_corename:
2354         coredump_finish(mm);
2355         revert_creds(old_cred);
2356 fail_creds:
2357         put_cred(cred);
2358 fail:
2359         return;
2360 }
2361
2362 /*
2363  * Core dumping helper functions.  These are the only things you should
2364  * do on a core-file: use only these functions to write out all the
2365  * necessary info.
2366  */
2367 int dump_write(struct file *file, const void *addr, int nr)
2368 {
2369         return access_ok(VERIFY_READ, addr, nr) && file->f_op->write(file, addr, nr, &file->f_pos) == nr;
2370 }
2371 EXPORT_SYMBOL(dump_write);
2372
2373 int dump_seek(struct file *file, loff_t off)
2374 {
2375         int ret = 1;
2376
2377         if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
2378                 if (file->f_op->llseek(file, off, SEEK_CUR) < 0)
2379                         return 0;
2380         } else {
2381                 char *buf = (char *)get_zeroed_page(GFP_KERNEL);
2382
2383                 if (!buf)
2384                         return 0;
2385                 while (off > 0) {
2386                         unsigned long n = off;
2387
2388                         if (n > PAGE_SIZE)
2389                                 n = PAGE_SIZE;
2390                         if (!dump_write(file, buf, n)) {
2391                                 ret = 0;
2392                                 break;
2393                         }
2394                         off -= n;
2395                 }
2396                 free_page((unsigned long)buf);
2397         }
2398         return ret;
2399 }
2400 EXPORT_SYMBOL(dump_seek);