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