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