vserver 2.0-rc4
[linux-2.6.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/config.h>
26 #include <linux/slab.h>
27 #include <linux/file.h>
28 #include <linux/mman.h>
29 #include <linux/a.out.h>
30 #include <linux/stat.h>
31 #include <linux/fcntl.h>
32 #include <linux/smp_lock.h>
33 #include <linux/init.h>
34 #include <linux/pagemap.h>
35 #include <linux/highmem.h>
36 #include <linux/spinlock.h>
37 #include <linux/key.h>
38 #include <linux/personality.h>
39 #include <linux/binfmts.h>
40 #include <linux/swap.h>
41 #include <linux/utsname.h>
42 #include <linux/module.h>
43 #include <linux/namei.h>
44 #include <linux/proc_fs.h>
45 #include <linux/ptrace.h>
46 #include <linux/mount.h>
47 #include <linux/security.h>
48 #include <linux/syscalls.h>
49 #include <linux/rmap.h>
50 #include <linux/acct.h>
51 #include <linux/vs_memory.h>
52
53 #include <asm/uaccess.h>
54 #include <asm/mmu_context.h>
55
56 #ifdef CONFIG_KMOD
57 #include <linux/kmod.h>
58 #endif
59
60 int core_uses_pid;
61 char core_pattern[65] = "core";
62 /* The maximal length of core_pattern is also specified in sysctl.c */
63
64 static struct linux_binfmt *formats;
65 static DEFINE_RWLOCK(binfmt_lock);
66
67 int register_binfmt(struct linux_binfmt * fmt)
68 {
69         struct linux_binfmt ** tmp = &formats;
70
71         if (!fmt)
72                 return -EINVAL;
73         if (fmt->next)
74                 return -EBUSY;
75         write_lock(&binfmt_lock);
76         while (*tmp) {
77                 if (fmt == *tmp) {
78                         write_unlock(&binfmt_lock);
79                         return -EBUSY;
80                 }
81                 tmp = &(*tmp)->next;
82         }
83         fmt->next = formats;
84         formats = fmt;
85         write_unlock(&binfmt_lock);
86         return 0;       
87 }
88
89 EXPORT_SYMBOL(register_binfmt);
90
91 int unregister_binfmt(struct linux_binfmt * fmt)
92 {
93         struct linux_binfmt ** tmp = &formats;
94
95         write_lock(&binfmt_lock);
96         while (*tmp) {
97                 if (fmt == *tmp) {
98                         *tmp = fmt->next;
99                         write_unlock(&binfmt_lock);
100                         return 0;
101                 }
102                 tmp = &(*tmp)->next;
103         }
104         write_unlock(&binfmt_lock);
105         return -EINVAL;
106 }
107
108 EXPORT_SYMBOL(unregister_binfmt);
109
110 static inline void put_binfmt(struct linux_binfmt * fmt)
111 {
112         module_put(fmt->module);
113 }
114
115 /*
116  * Note that a shared library must be both readable and executable due to
117  * security reasons.
118  *
119  * Also note that we take the address to load from from the file itself.
120  */
121 asmlinkage long sys_uselib(const char __user * library)
122 {
123         struct file * file;
124         struct nameidata nd;
125         int error;
126
127         nd.intent.open.flags = FMODE_READ;
128         error = __user_walk(library, LOOKUP_FOLLOW|LOOKUP_OPEN, &nd);
129         if (error)
130                 goto out;
131
132         error = -EINVAL;
133         if (!S_ISREG(nd.dentry->d_inode->i_mode))
134                 goto exit;
135
136         error = permission(nd.dentry->d_inode, MAY_READ | MAY_EXEC, &nd);
137         if (error)
138                 goto exit;
139
140         file = dentry_open(nd.dentry, nd.mnt, O_RDONLY);
141         error = PTR_ERR(file);
142         if (IS_ERR(file))
143                 goto out;
144
145         error = -ENOEXEC;
146         if(file->f_op) {
147                 struct linux_binfmt * fmt;
148
149                 read_lock(&binfmt_lock);
150                 for (fmt = formats ; fmt ; fmt = fmt->next) {
151                         if (!fmt->load_shlib)
152                                 continue;
153                         if (!try_module_get(fmt->module))
154                                 continue;
155                         read_unlock(&binfmt_lock);
156                         error = fmt->load_shlib(file);
157                         read_lock(&binfmt_lock);
158                         put_binfmt(fmt);
159                         if (error != -ENOEXEC)
160                                 break;
161                 }
162                 read_unlock(&binfmt_lock);
163         }
164         fput(file);
165 out:
166         return error;
167 exit:
168         path_release(&nd);
169         goto out;
170 }
171
172 /*
173  * count() counts the number of strings in array ARGV.
174  */
175 static int count(char __user * __user * argv, int max)
176 {
177         int i = 0;
178
179         if (argv != NULL) {
180                 for (;;) {
181                         char __user * p;
182
183                         if (get_user(p, argv))
184                                 return -EFAULT;
185                         if (!p)
186                                 break;
187                         argv++;
188                         if(++i > max)
189                                 return -E2BIG;
190                         cond_resched();
191                 }
192         }
193         return i;
194 }
195
196 /*
197  * 'copy_strings()' copies argument/environment strings from user
198  * memory to free pages in kernel mem. These are in a format ready
199  * to be put directly into the top of new user memory.
200  */
201 int copy_strings(int argc,char __user * __user * argv, struct linux_binprm *bprm)
202 {
203         struct page *kmapped_page = NULL;
204         char *kaddr = NULL;
205         int ret;
206
207         while (argc-- > 0) {
208                 char __user *str;
209                 int len;
210                 unsigned long pos;
211
212                 if (get_user(str, argv+argc) ||
213                                 !(len = strnlen_user(str, bprm->p))) {
214                         ret = -EFAULT;
215                         goto out;
216                 }
217
218                 if (bprm->p < len)  {
219                         ret = -E2BIG;
220                         goto out;
221                 }
222
223                 bprm->p -= len;
224                 /* XXX: add architecture specific overflow check here. */
225                 pos = bprm->p;
226
227                 while (len > 0) {
228                         int i, new, err;
229                         int offset, bytes_to_copy;
230                         struct page *page;
231
232                         offset = pos % PAGE_SIZE;
233                         i = pos/PAGE_SIZE;
234                         page = bprm->page[i];
235                         new = 0;
236                         if (!page) {
237                                 page = alloc_page(GFP_HIGHUSER);
238                                 bprm->page[i] = page;
239                                 if (!page) {
240                                         ret = -ENOMEM;
241                                         goto out;
242                                 }
243                                 new = 1;
244                         }
245
246                         if (page != kmapped_page) {
247                                 if (kmapped_page)
248                                         kunmap(kmapped_page);
249                                 kmapped_page = page;
250                                 kaddr = kmap(kmapped_page);
251                         }
252                         if (new && offset)
253                                 memset(kaddr, 0, offset);
254                         bytes_to_copy = PAGE_SIZE - offset;
255                         if (bytes_to_copy > len) {
256                                 bytes_to_copy = len;
257                                 if (new)
258                                         memset(kaddr+offset+len, 0,
259                                                 PAGE_SIZE-offset-len);
260                         }
261                         err = copy_from_user(kaddr+offset, str, bytes_to_copy);
262                         if (err) {
263                                 ret = -EFAULT;
264                                 goto out;
265                         }
266
267                         pos += bytes_to_copy;
268                         str += bytes_to_copy;
269                         len -= bytes_to_copy;
270                 }
271         }
272         ret = 0;
273 out:
274         if (kmapped_page)
275                 kunmap(kmapped_page);
276         return ret;
277 }
278
279 /*
280  * Like copy_strings, but get argv and its values from kernel memory.
281  */
282 int copy_strings_kernel(int argc,char ** argv, struct linux_binprm *bprm)
283 {
284         int r;
285         mm_segment_t oldfs = get_fs();
286         set_fs(KERNEL_DS);
287         r = copy_strings(argc, (char __user * __user *)argv, bprm);
288         set_fs(oldfs);
289         return r;
290 }
291
292 EXPORT_SYMBOL(copy_strings_kernel);
293
294 #ifdef CONFIG_MMU
295 /*
296  * This routine is used to map in a page into an address space: needed by
297  * execve() for the initial stack and environment pages.
298  *
299  * vma->vm_mm->mmap_sem is held for writing.
300  */
301 void install_arg_page(struct vm_area_struct *vma,
302                         struct page *page, unsigned long address)
303 {
304         struct mm_struct *mm = vma->vm_mm;
305         pgd_t * pgd;
306         pud_t * pud;
307         pmd_t * pmd;
308         pte_t * pte;
309
310         if (unlikely(anon_vma_prepare(vma)))
311                 goto out_sig;
312
313         flush_dcache_page(page);
314         pgd = pgd_offset(mm, address);
315
316         spin_lock(&mm->page_table_lock);
317         pud = pud_alloc(mm, pgd, address);
318         if (!pud)
319                 goto out;
320         pmd = pmd_alloc(mm, pud, address);
321         if (!pmd)
322                 goto out;
323         pte = pte_alloc_map(mm, pmd, address);
324         if (!pte)
325                 goto out;
326         if (!pte_none(*pte)) {
327                 pte_unmap(pte);
328                 goto out;
329         }
330         vx_rsspages_inc(mm);
331         lru_cache_add_active(page);
332         set_pte(pte, pte_mkdirty(pte_mkwrite(mk_pte(
333                                         page, vma->vm_page_prot))));
334         page_add_anon_rmap(page, vma, address);
335         pte_unmap(pte);
336         spin_unlock(&mm->page_table_lock);
337
338         /* no need for flush_tlb */
339         return;
340 out:
341         spin_unlock(&mm->page_table_lock);
342 out_sig:
343         __free_page(page);
344         force_sig(SIGKILL, current);
345 }
346
347 #define EXTRA_STACK_VM_PAGES    20      /* random */
348
349 int setup_arg_pages(struct linux_binprm *bprm,
350                     unsigned long stack_top,
351                     int executable_stack)
352 {
353         unsigned long stack_base;
354         struct vm_area_struct *mpnt;
355         struct mm_struct *mm = current->mm;
356         int i, ret;
357         long arg_size;
358
359 #ifdef CONFIG_STACK_GROWSUP
360         /* Move the argument and environment strings to the bottom of the
361          * stack space.
362          */
363         int offset, j;
364         char *to, *from;
365
366         /* Start by shifting all the pages down */
367         i = 0;
368         for (j = 0; j < MAX_ARG_PAGES; j++) {
369                 struct page *page = bprm->page[j];
370                 if (!page)
371                         continue;
372                 bprm->page[i++] = page;
373         }
374
375         /* Now move them within their pages */
376         offset = bprm->p % PAGE_SIZE;
377         to = kmap(bprm->page[0]);
378         for (j = 1; j < i; j++) {
379                 memmove(to, to + offset, PAGE_SIZE - offset);
380                 from = kmap(bprm->page[j]);
381                 memcpy(to + PAGE_SIZE - offset, from, offset);
382                 kunmap(bprm->page[j - 1]);
383                 to = from;
384         }
385         memmove(to, to + offset, PAGE_SIZE - offset);
386         kunmap(bprm->page[j - 1]);
387
388         /* Limit stack size to 1GB */
389         stack_base = current->signal->rlim[RLIMIT_STACK].rlim_max;
390         if (stack_base > (1 << 30))
391                 stack_base = 1 << 30;
392         stack_base = PAGE_ALIGN(stack_top - stack_base);
393
394         /* Adjust bprm->p to point to the end of the strings. */
395         bprm->p = stack_base + PAGE_SIZE * i - offset;
396
397         mm->arg_start = stack_base;
398         arg_size = i << PAGE_SHIFT;
399
400         /* zero pages that were copied above */
401         while (i < MAX_ARG_PAGES)
402                 bprm->page[i++] = NULL;
403 #else
404         stack_base = stack_top - MAX_ARG_PAGES * PAGE_SIZE;
405         bprm->p += stack_base;
406         mm->arg_start = bprm->p;
407         arg_size = stack_top - (PAGE_MASK & (unsigned long) mm->arg_start);
408 #endif
409
410         arg_size += EXTRA_STACK_VM_PAGES * PAGE_SIZE;
411
412         if (bprm->loader)
413                 bprm->loader += stack_base;
414         bprm->exec += stack_base;
415
416         mpnt = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
417         if (!mpnt)
418                 return -ENOMEM;
419
420         if (security_vm_enough_memory(arg_size >> PAGE_SHIFT) ||
421                 !vx_vmpages_avail(mm, arg_size >> PAGE_SHIFT)) {
422                 kmem_cache_free(vm_area_cachep, mpnt);
423                 return -ENOMEM;
424         }
425
426         memset(mpnt, 0, sizeof(*mpnt));
427
428         down_write(&mm->mmap_sem);
429         {
430                 mpnt->vm_mm = mm;
431 #ifdef CONFIG_STACK_GROWSUP
432                 mpnt->vm_start = stack_base;
433                 mpnt->vm_end = stack_base + arg_size;
434 #else
435                 mpnt->vm_end = stack_top;
436                 mpnt->vm_start = mpnt->vm_end - arg_size;
437 #endif
438                 /* Adjust stack execute permissions; explicitly enable
439                  * for EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X
440                  * and leave alone (arch default) otherwise. */
441                 if (unlikely(executable_stack == EXSTACK_ENABLE_X))
442                         mpnt->vm_flags = VM_STACK_FLAGS |  VM_EXEC;
443                 else if (executable_stack == EXSTACK_DISABLE_X)
444                         mpnt->vm_flags = VM_STACK_FLAGS & ~VM_EXEC;
445                 else
446                         mpnt->vm_flags = VM_STACK_FLAGS;
447                 mpnt->vm_flags |= mm->def_flags;
448                 mpnt->vm_page_prot = protection_map[mpnt->vm_flags & 0x7];
449                 if ((ret = insert_vm_struct(mm, mpnt))) {
450                         up_write(&mm->mmap_sem);
451                         kmem_cache_free(vm_area_cachep, mpnt);
452                         return ret;
453                 }
454                 vx_vmpages_sub(mm, mm->total_vm - vma_pages(mpnt));
455                 mm->stack_vm = mm->total_vm;
456         }
457
458         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
459                 struct page *page = bprm->page[i];
460                 if (page) {
461                         bprm->page[i] = NULL;
462                         install_arg_page(mpnt, page, stack_base);
463                 }
464                 stack_base += PAGE_SIZE;
465         }
466         up_write(&mm->mmap_sem);
467         
468         return 0;
469 }
470
471 EXPORT_SYMBOL(setup_arg_pages);
472
473 #define free_arg_pages(bprm) do { } while (0)
474
475 #else
476
477 static inline void free_arg_pages(struct linux_binprm *bprm)
478 {
479         int i;
480
481         for (i = 0; i < MAX_ARG_PAGES; i++) {
482                 if (bprm->page[i])
483                         __free_page(bprm->page[i]);
484                 bprm->page[i] = NULL;
485         }
486 }
487
488 #endif /* CONFIG_MMU */
489
490 struct file *open_exec(const char *name)
491 {
492         struct nameidata nd;
493         int err;
494         struct file *file;
495
496         nd.intent.open.flags = FMODE_READ;
497         err = path_lookup(name, LOOKUP_FOLLOW|LOOKUP_OPEN, &nd);
498         file = ERR_PTR(err);
499
500         if (!err) {
501                 struct inode *inode = nd.dentry->d_inode;
502                 file = ERR_PTR(-EACCES);
503                 if (!(nd.mnt->mnt_flags & MNT_NOEXEC) &&
504                     S_ISREG(inode->i_mode)) {
505                         int err = permission(inode, MAY_EXEC, &nd);
506                         if (!err && !(inode->i_mode & 0111))
507                                 err = -EACCES;
508                         file = ERR_PTR(err);
509                         if (!err) {
510                                 file = dentry_open(nd.dentry, nd.mnt, O_RDONLY);
511                                 if (!IS_ERR(file)) {
512                                         err = deny_write_access(file);
513                                         if (err) {
514                                                 fput(file);
515                                                 file = ERR_PTR(err);
516                                         }
517                                 }
518 out:
519                                 return file;
520                         }
521                 }
522                 path_release(&nd);
523         }
524         goto out;
525 }
526
527 EXPORT_SYMBOL(open_exec);
528
529 int kernel_read(struct file *file, unsigned long offset,
530         char *addr, unsigned long count)
531 {
532         mm_segment_t old_fs;
533         loff_t pos = offset;
534         int result;
535
536         old_fs = get_fs();
537         set_fs(get_ds());
538         /* The cast to a user pointer is valid due to the set_fs() */
539         result = vfs_read(file, (void __user *)addr, count, &pos);
540         set_fs(old_fs);
541         return result;
542 }
543
544 EXPORT_SYMBOL(kernel_read);
545
546 static int exec_mmap(struct mm_struct *mm)
547 {
548         struct task_struct *tsk;
549         struct mm_struct * old_mm, *active_mm;
550
551         /* Notify parent that we're no longer interested in the old VM */
552         tsk = current;
553         old_mm = current->mm;
554         mm_release(tsk, old_mm);
555
556         if (old_mm) {
557                 /*
558                  * Make sure that if there is a core dump in progress
559                  * for the old mm, we get out and die instead of going
560                  * through with the exec.  We must hold mmap_sem around
561                  * checking core_waiters and changing tsk->mm.  The
562                  * core-inducing thread will increment core_waiters for
563                  * each thread whose ->mm == old_mm.
564                  */
565                 down_read(&old_mm->mmap_sem);
566                 if (unlikely(old_mm->core_waiters)) {
567                         up_read(&old_mm->mmap_sem);
568                         return -EINTR;
569                 }
570         }
571         task_lock(tsk);
572         active_mm = tsk->active_mm;
573         tsk->mm = mm;
574         tsk->active_mm = mm;
575         activate_mm(active_mm, mm);
576         task_unlock(tsk);
577         arch_pick_mmap_layout(mm);
578         if (old_mm) {
579                 up_read(&old_mm->mmap_sem);
580                 if (active_mm != old_mm) BUG();
581                 mmput(old_mm);
582                 return 0;
583         }
584         mmdrop(active_mm);
585         return 0;
586 }
587
588 /*
589  * This function makes sure the current process has its own signal table,
590  * so that flush_signal_handlers can later reset the handlers without
591  * disturbing other processes.  (Other processes might share the signal
592  * table via the CLONE_SIGHAND option to clone().)
593  */
594 static inline int de_thread(struct task_struct *tsk)
595 {
596         struct signal_struct *sig = tsk->signal;
597         struct sighand_struct *newsighand, *oldsighand = tsk->sighand;
598         spinlock_t *lock = &oldsighand->siglock;
599         int count;
600
601         /*
602          * If we don't share sighandlers, then we aren't sharing anything
603          * and we can just re-use it all.
604          */
605         if (atomic_read(&oldsighand->count) <= 1) {
606                 BUG_ON(atomic_read(&sig->count) != 1);
607                 exit_itimers(sig);
608                 return 0;
609         }
610
611         newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
612         if (!newsighand)
613                 return -ENOMEM;
614
615         if (thread_group_empty(current))
616                 goto no_thread_group;
617
618         /*
619          * Kill all other threads in the thread group.
620          * We must hold tasklist_lock to call zap_other_threads.
621          */
622         read_lock(&tasklist_lock);
623         spin_lock_irq(lock);
624         if (sig->flags & SIGNAL_GROUP_EXIT) {
625                 /*
626                  * Another group action in progress, just
627                  * return so that the signal is processed.
628                  */
629                 spin_unlock_irq(lock);
630                 read_unlock(&tasklist_lock);
631                 kmem_cache_free(sighand_cachep, newsighand);
632                 return -EAGAIN;
633         }
634         zap_other_threads(current);
635         read_unlock(&tasklist_lock);
636
637         /*
638          * Account for the thread group leader hanging around:
639          */
640         count = 2;
641         if (thread_group_leader(current))
642                 count = 1;
643         while (atomic_read(&sig->count) > count) {
644                 sig->group_exit_task = current;
645                 sig->notify_count = count;
646                 __set_current_state(TASK_UNINTERRUPTIBLE);
647                 spin_unlock_irq(lock);
648                 schedule();
649                 spin_lock_irq(lock);
650         }
651         sig->group_exit_task = NULL;
652         sig->notify_count = 0;
653         spin_unlock_irq(lock);
654
655         /*
656          * At this point all other threads have exited, all we have to
657          * do is to wait for the thread group leader to become inactive,
658          * and to assume its PID:
659          */
660         if (!thread_group_leader(current)) {
661                 struct task_struct *leader = current->group_leader, *parent;
662                 struct dentry *proc_dentry1, *proc_dentry2;
663                 unsigned long exit_state, ptrace;
664
665                 /*
666                  * Wait for the thread group leader to be a zombie.
667                  * It should already be zombie at this point, most
668                  * of the time.
669                  */
670                 while (leader->exit_state != EXIT_ZOMBIE)
671                         yield();
672
673                 spin_lock(&leader->proc_lock);
674                 spin_lock(&current->proc_lock);
675                 proc_dentry1 = proc_pid_unhash(current);
676                 proc_dentry2 = proc_pid_unhash(leader);
677                 write_lock_irq(&tasklist_lock);
678
679                 if (leader->tgid != current->tgid)
680                         BUG();
681                 if (current->pid == current->tgid)
682                         BUG();
683                 /*
684                  * An exec() starts a new thread group with the
685                  * TGID of the previous thread group. Rehash the
686                  * two threads with a switched PID, and release
687                  * the former thread group leader:
688                  */
689                 ptrace = leader->ptrace;
690                 parent = leader->parent;
691                 if (unlikely(ptrace) && unlikely(parent == current)) {
692                         /*
693                          * Joker was ptracing his own group leader,
694                          * and now he wants to be his own parent!
695                          * We can't have that.
696                          */
697                         ptrace = 0;
698                 }
699
700                 ptrace_unlink(current);
701                 ptrace_unlink(leader);
702                 remove_parent(current);
703                 remove_parent(leader);
704
705                 switch_exec_pids(leader, current);
706
707                 current->parent = current->real_parent = leader->real_parent;
708                 leader->parent = leader->real_parent = child_reaper;
709                 current->group_leader = current;
710                 leader->group_leader = leader;
711
712                 add_parent(current, current->parent);
713                 add_parent(leader, leader->parent);
714                 if (ptrace) {
715                         current->ptrace = ptrace;
716                         __ptrace_link(current, parent);
717                 }
718
719                 list_del(&current->tasks);
720                 list_add_tail(&current->tasks, &init_task.tasks);
721                 current->exit_signal = SIGCHLD;
722                 exit_state = leader->exit_state;
723
724                 write_unlock_irq(&tasklist_lock);
725                 spin_unlock(&leader->proc_lock);
726                 spin_unlock(&current->proc_lock);
727                 proc_pid_flush(proc_dentry1);
728                 proc_pid_flush(proc_dentry2);
729
730                 if (exit_state != EXIT_ZOMBIE)
731                         BUG();
732                 release_task(leader);
733         }
734
735         /*
736          * Now there are really no other threads at all,
737          * so it's safe to stop telling them to kill themselves.
738          */
739         sig->flags = 0;
740
741 no_thread_group:
742         BUG_ON(atomic_read(&sig->count) != 1);
743         exit_itimers(sig);
744
745         if (atomic_read(&oldsighand->count) == 1) {
746                 /*
747                  * Now that we nuked the rest of the thread group,
748                  * it turns out we are not sharing sighand any more either.
749                  * So we can just keep it.
750                  */
751                 kmem_cache_free(sighand_cachep, newsighand);
752         } else {
753                 /*
754                  * Move our state over to newsighand and switch it in.
755                  */
756                 spin_lock_init(&newsighand->siglock);
757                 atomic_set(&newsighand->count, 1);
758                 memcpy(newsighand->action, oldsighand->action,
759                        sizeof(newsighand->action));
760
761                 write_lock_irq(&tasklist_lock);
762                 spin_lock(&oldsighand->siglock);
763                 spin_lock(&newsighand->siglock);
764
765                 current->sighand = newsighand;
766                 recalc_sigpending();
767
768                 spin_unlock(&newsighand->siglock);
769                 spin_unlock(&oldsighand->siglock);
770                 write_unlock_irq(&tasklist_lock);
771
772                 if (atomic_dec_and_test(&oldsighand->count))
773                         kmem_cache_free(sighand_cachep, oldsighand);
774         }
775
776         if (!thread_group_empty(current))
777                 BUG();
778         if (!thread_group_leader(current))
779                 BUG();
780         return 0;
781 }
782         
783 /*
784  * These functions flushes out all traces of the currently running executable
785  * so that a new one can be started
786  */
787
788 static inline void flush_old_files(struct files_struct * files)
789 {
790         long j = -1;
791
792         spin_lock(&files->file_lock);
793         for (;;) {
794                 unsigned long set, i;
795
796                 j++;
797                 i = j * __NFDBITS;
798                 if (i >= files->max_fds || i >= files->max_fdset)
799                         break;
800                 set = files->close_on_exec->fds_bits[j];
801                 if (!set)
802                         continue;
803                 files->close_on_exec->fds_bits[j] = 0;
804                 spin_unlock(&files->file_lock);
805                 for ( ; set ; i++,set >>= 1) {
806                         if (set & 1) {
807                                 sys_close(i);
808                         }
809                 }
810                 spin_lock(&files->file_lock);
811
812         }
813         spin_unlock(&files->file_lock);
814 }
815
816 void get_task_comm(char *buf, struct task_struct *tsk)
817 {
818         /* buf must be at least sizeof(tsk->comm) in size */
819         task_lock(tsk);
820         strncpy(buf, tsk->comm, sizeof(tsk->comm));
821         task_unlock(tsk);
822 }
823
824 void set_task_comm(struct task_struct *tsk, char *buf)
825 {
826         task_lock(tsk);
827         strlcpy(tsk->comm, buf, sizeof(tsk->comm));
828         task_unlock(tsk);
829 }
830
831 int flush_old_exec(struct linux_binprm * bprm)
832 {
833         char * name;
834         int i, ch, retval;
835         struct files_struct *files;
836         char tcomm[sizeof(current->comm)];
837
838         /*
839          * Make sure we have a private signal table and that
840          * we are unassociated from the previous thread group.
841          */
842         retval = de_thread(current);
843         if (retval)
844                 goto out;
845
846         /*
847          * Make sure we have private file handles. Ask the
848          * fork helper to do the work for us and the exit
849          * helper to do the cleanup of the old one.
850          */
851         files = current->files;         /* refcounted so safe to hold */
852         retval = unshare_files();
853         if (retval)
854                 goto out;
855         /*
856          * Release all of the old mmap stuff
857          */
858         retval = exec_mmap(bprm->mm);
859         if (retval)
860                 goto mmap_failed;
861
862         bprm->mm = NULL;                /* We're using it now */
863
864         /* This is the point of no return */
865         steal_locks(files);
866         put_files_struct(files);
867
868         current->sas_ss_sp = current->sas_ss_size = 0;
869
870         if (current->euid == current->uid && current->egid == current->gid)
871                 current->mm->dumpable = 1;
872         name = bprm->filename;
873         for (i=0; (ch = *(name++)) != '\0';) {
874                 if (ch == '/')
875                         i = 0;
876                 else
877                         if (i < (sizeof(tcomm) - 1))
878                                 tcomm[i++] = ch;
879         }
880         tcomm[i] = '\0';
881         set_task_comm(current, tcomm);
882
883         flush_thread();
884
885         if (bprm->e_uid != current->euid || bprm->e_gid != current->egid || 
886             permission(bprm->file->f_dentry->d_inode,MAY_READ, NULL) ||
887             (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP)) {
888                 suid_keys(current);
889                 current->mm->dumpable = 0;
890         }
891
892         /* An exec changes our domain. We are no longer part of the thread
893            group */
894
895         current->self_exec_id++;
896                         
897         flush_signal_handlers(current, 0);
898         flush_old_files(current->files);
899
900         return 0;
901
902 mmap_failed:
903         put_files_struct(current->files);
904         current->files = files;
905 out:
906         return retval;
907 }
908
909 EXPORT_SYMBOL(flush_old_exec);
910
911 /* 
912  * Fill the binprm structure from the inode. 
913  * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
914  */
915 int prepare_binprm(struct linux_binprm *bprm)
916 {
917         int mode;
918         struct inode * inode = bprm->file->f_dentry->d_inode;
919         int retval;
920
921         mode = inode->i_mode;
922         /*
923          * Check execute perms again - if the caller has CAP_DAC_OVERRIDE,
924          * generic_permission lets a non-executable through
925          */
926         if (!(mode & 0111))     /* with at least _one_ execute bit set */
927                 return -EACCES;
928         if (bprm->file->f_op == NULL)
929                 return -EACCES;
930
931         bprm->e_uid = current->euid;
932         bprm->e_gid = current->egid;
933
934         if(!(bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)) {
935                 /* Set-uid? */
936                 if (mode & S_ISUID) {
937                         current->personality &= ~PER_CLEAR_ON_SETID;
938                         bprm->e_uid = inode->i_uid;
939                 }
940
941                 /* Set-gid? */
942                 /*
943                  * If setgid is set but no group execute bit then this
944                  * is a candidate for mandatory locking, not a setgid
945                  * executable.
946                  */
947                 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
948                         current->personality &= ~PER_CLEAR_ON_SETID;
949                         bprm->e_gid = inode->i_gid;
950                 }
951         }
952
953         /* fill in binprm security blob */
954         retval = security_bprm_set(bprm);
955         if (retval)
956                 return retval;
957
958         memset(bprm->buf,0,BINPRM_BUF_SIZE);
959         return kernel_read(bprm->file,0,bprm->buf,BINPRM_BUF_SIZE);
960 }
961
962 EXPORT_SYMBOL(prepare_binprm);
963
964 static inline int unsafe_exec(struct task_struct *p)
965 {
966         int unsafe = 0;
967         if (p->ptrace & PT_PTRACED) {
968                 if (p->ptrace & PT_PTRACE_CAP)
969                         unsafe |= LSM_UNSAFE_PTRACE_CAP;
970                 else
971                         unsafe |= LSM_UNSAFE_PTRACE;
972         }
973         if (atomic_read(&p->fs->count) > 1 ||
974             atomic_read(&p->files->count) > 1 ||
975             atomic_read(&p->sighand->count) > 1)
976                 unsafe |= LSM_UNSAFE_SHARE;
977
978         return unsafe;
979 }
980
981 void compute_creds(struct linux_binprm *bprm)
982 {
983         int unsafe;
984
985         if (bprm->e_uid != current->uid)
986                 suid_keys(current);
987         exec_keys(current);
988
989         task_lock(current);
990         unsafe = unsafe_exec(current);
991         security_bprm_apply_creds(bprm, unsafe);
992         task_unlock(current);
993         security_bprm_post_apply_creds(bprm);
994 }
995
996 EXPORT_SYMBOL(compute_creds);
997
998 void remove_arg_zero(struct linux_binprm *bprm)
999 {
1000         if (bprm->argc) {
1001                 unsigned long offset;
1002                 char * kaddr;
1003                 struct page *page;
1004
1005                 offset = bprm->p % PAGE_SIZE;
1006                 goto inside;
1007
1008                 while (bprm->p++, *(kaddr+offset++)) {
1009                         if (offset != PAGE_SIZE)
1010                                 continue;
1011                         offset = 0;
1012                         kunmap_atomic(kaddr, KM_USER0);
1013 inside:
1014                         page = bprm->page[bprm->p/PAGE_SIZE];
1015                         kaddr = kmap_atomic(page, KM_USER0);
1016                 }
1017                 kunmap_atomic(kaddr, KM_USER0);
1018                 bprm->argc--;
1019         }
1020 }
1021
1022 EXPORT_SYMBOL(remove_arg_zero);
1023
1024 /*
1025  * cycle the list of binary formats handler, until one recognizes the image
1026  */
1027 int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs)
1028 {
1029         int try,retval;
1030         struct linux_binfmt *fmt;
1031 #ifdef __alpha__
1032         /* handle /sbin/loader.. */
1033         {
1034             struct exec * eh = (struct exec *) bprm->buf;
1035
1036             if (!bprm->loader && eh->fh.f_magic == 0x183 &&
1037                 (eh->fh.f_flags & 0x3000) == 0x3000)
1038             {
1039                 struct file * file;
1040                 unsigned long loader;
1041
1042                 allow_write_access(bprm->file);
1043                 fput(bprm->file);
1044                 bprm->file = NULL;
1045
1046                 loader = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1047
1048                 file = open_exec("/sbin/loader");
1049                 retval = PTR_ERR(file);
1050                 if (IS_ERR(file))
1051                         return retval;
1052
1053                 /* Remember if the application is TASO.  */
1054                 bprm->sh_bang = eh->ah.entry < 0x100000000UL;
1055
1056                 bprm->file = file;
1057                 bprm->loader = loader;
1058                 retval = prepare_binprm(bprm);
1059                 if (retval<0)
1060                         return retval;
1061                 /* should call search_binary_handler recursively here,
1062                    but it does not matter */
1063             }
1064         }
1065 #endif
1066         retval = security_bprm_check(bprm);
1067         if (retval)
1068                 return retval;
1069
1070         /* kernel module loader fixup */
1071         /* so we don't try to load run modprobe in kernel space. */
1072         set_fs(USER_DS);
1073         retval = -ENOENT;
1074         for (try=0; try<2; try++) {
1075                 read_lock(&binfmt_lock);
1076                 for (fmt = formats ; fmt ; fmt = fmt->next) {
1077                         int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
1078                         if (!fn)
1079                                 continue;
1080                         if (!try_module_get(fmt->module))
1081                                 continue;
1082                         read_unlock(&binfmt_lock);
1083                         retval = fn(bprm, regs);
1084                         if (retval >= 0) {
1085                                 put_binfmt(fmt);
1086                                 allow_write_access(bprm->file);
1087                                 if (bprm->file)
1088                                         fput(bprm->file);
1089                                 bprm->file = NULL;
1090                                 current->did_exec = 1;
1091                                 return retval;
1092                         }
1093                         read_lock(&binfmt_lock);
1094                         put_binfmt(fmt);
1095                         if (retval != -ENOEXEC || bprm->mm == NULL)
1096                                 break;
1097                         if (!bprm->file) {
1098                                 read_unlock(&binfmt_lock);
1099                                 return retval;
1100                         }
1101                 }
1102                 read_unlock(&binfmt_lock);
1103                 if (retval != -ENOEXEC || bprm->mm == NULL) {
1104                         break;
1105 #ifdef CONFIG_KMOD
1106                 }else{
1107 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
1108                         if (printable(bprm->buf[0]) &&
1109                             printable(bprm->buf[1]) &&
1110                             printable(bprm->buf[2]) &&
1111                             printable(bprm->buf[3]))
1112                                 break; /* -ENOEXEC */
1113                         request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
1114 #endif
1115                 }
1116         }
1117         return retval;
1118 }
1119
1120 EXPORT_SYMBOL(search_binary_handler);
1121
1122 /*
1123  * sys_execve() executes a new program.
1124  */
1125 int do_execve(char * filename,
1126         char __user *__user *argv,
1127         char __user *__user *envp,
1128         struct pt_regs * regs)
1129 {
1130         struct linux_binprm *bprm;
1131         struct file *file;
1132         int retval;
1133         int i;
1134
1135         retval = -ENOMEM;
1136         bprm = kmalloc(sizeof(*bprm), GFP_KERNEL);
1137         if (!bprm)
1138                 goto out_ret;
1139         memset(bprm, 0, sizeof(*bprm));
1140
1141         file = open_exec(filename);
1142         retval = PTR_ERR(file);
1143         if (IS_ERR(file))
1144                 goto out_kfree;
1145
1146         sched_exec();
1147
1148         bprm->p = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1149
1150         bprm->file = file;
1151         bprm->filename = filename;
1152         bprm->interp = filename;
1153         bprm->mm = mm_alloc();
1154         retval = -ENOMEM;
1155         if (!bprm->mm)
1156                 goto out_file;
1157
1158         retval = init_new_context(current, bprm->mm);
1159         if (retval < 0)
1160                 goto out_mm;
1161
1162         bprm->argc = count(argv, bprm->p / sizeof(void *));
1163         if ((retval = bprm->argc) < 0)
1164                 goto out_mm;
1165
1166         bprm->envc = count(envp, bprm->p / sizeof(void *));
1167         if ((retval = bprm->envc) < 0)
1168                 goto out_mm;
1169
1170         retval = security_bprm_alloc(bprm);
1171         if (retval)
1172                 goto out;
1173
1174         retval = prepare_binprm(bprm);
1175         if (retval < 0)
1176                 goto out;
1177
1178         retval = copy_strings_kernel(1, &bprm->filename, bprm);
1179         if (retval < 0)
1180                 goto out;
1181
1182         bprm->exec = bprm->p;
1183         retval = copy_strings(bprm->envc, envp, bprm);
1184         if (retval < 0)
1185                 goto out;
1186
1187         retval = copy_strings(bprm->argc, argv, bprm);
1188         if (retval < 0)
1189                 goto out;
1190
1191         retval = search_binary_handler(bprm,regs);
1192         if (retval >= 0) {
1193                 free_arg_pages(bprm);
1194
1195                 /* execve success */
1196                 security_bprm_free(bprm);
1197                 acct_update_integrals();
1198                 update_mem_hiwater();
1199                 kfree(bprm);
1200                 return retval;
1201         }
1202
1203 out:
1204         /* Something went wrong, return the inode and free the argument pages*/
1205         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
1206                 struct page * page = bprm->page[i];
1207                 if (page)
1208                         __free_page(page);
1209         }
1210
1211         if (bprm->security)
1212                 security_bprm_free(bprm);
1213
1214 out_mm:
1215         if (bprm->mm)
1216                 mmdrop(bprm->mm);
1217
1218 out_file:
1219         if (bprm->file) {
1220                 allow_write_access(bprm->file);
1221                 fput(bprm->file);
1222         }
1223
1224 out_kfree:
1225         kfree(bprm);
1226
1227 out_ret:
1228         return retval;
1229 }
1230
1231 int set_binfmt(struct linux_binfmt *new)
1232 {
1233         struct linux_binfmt *old = current->binfmt;
1234
1235         if (new) {
1236                 if (!try_module_get(new->module))
1237                         return -1;
1238         }
1239         current->binfmt = new;
1240         if (old)
1241                 module_put(old->module);
1242         return 0;
1243 }
1244
1245 EXPORT_SYMBOL(set_binfmt);
1246
1247 #define CORENAME_MAX_SIZE 64
1248
1249 /* format_corename will inspect the pattern parameter, and output a
1250  * name into corename, which must have space for at least
1251  * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
1252  */
1253 static void format_corename(char *corename, const char *pattern, long signr)
1254 {
1255         const char *pat_ptr = pattern;
1256         char *out_ptr = corename;
1257         char *const out_end = corename + CORENAME_MAX_SIZE;
1258         int rc;
1259         int pid_in_pattern = 0;
1260
1261         /* Repeat as long as we have more pattern to process and more output
1262            space */
1263         while (*pat_ptr) {
1264                 if (*pat_ptr != '%') {
1265                         if (out_ptr == out_end)
1266                                 goto out;
1267                         *out_ptr++ = *pat_ptr++;
1268                 } else {
1269                         switch (*++pat_ptr) {
1270                         case 0:
1271                                 goto out;
1272                         /* Double percent, output one percent */
1273                         case '%':
1274                                 if (out_ptr == out_end)
1275                                         goto out;
1276                                 *out_ptr++ = '%';
1277                                 break;
1278                         /* pid */
1279                         case 'p':
1280                                 pid_in_pattern = 1;
1281                                 rc = snprintf(out_ptr, out_end - out_ptr,
1282                                               "%d", current->tgid);
1283                                 if (rc > out_end - out_ptr)
1284                                         goto out;
1285                                 out_ptr += rc;
1286                                 break;
1287                         /* uid */
1288                         case 'u':
1289                                 rc = snprintf(out_ptr, out_end - out_ptr,
1290                                               "%d", current->uid);
1291                                 if (rc > out_end - out_ptr)
1292                                         goto out;
1293                                 out_ptr += rc;
1294                                 break;
1295                         /* gid */
1296                         case 'g':
1297                                 rc = snprintf(out_ptr, out_end - out_ptr,
1298                                               "%d", current->gid);
1299                                 if (rc > out_end - out_ptr)
1300                                         goto out;
1301                                 out_ptr += rc;
1302                                 break;
1303                         /* signal that caused the coredump */
1304                         case 's':
1305                                 rc = snprintf(out_ptr, out_end - out_ptr,
1306                                               "%ld", signr);
1307                                 if (rc > out_end - out_ptr)
1308                                         goto out;
1309                                 out_ptr += rc;
1310                                 break;
1311                         /* UNIX time of coredump */
1312                         case 't': {
1313                                 struct timeval tv;
1314                                 do_gettimeofday(&tv);
1315                                 rc = snprintf(out_ptr, out_end - out_ptr,
1316                                               "%lu", tv.tv_sec);
1317                                 if (rc > out_end - out_ptr)
1318                                         goto out;
1319                                 out_ptr += rc;
1320                                 break;
1321                         }
1322                         /* hostname */
1323                         case 'h':
1324                                 down_read(&uts_sem);
1325                                 rc = snprintf(out_ptr, out_end - out_ptr,
1326                                               "%s", system_utsname.nodename);
1327                                 up_read(&uts_sem);
1328                                 if (rc > out_end - out_ptr)
1329                                         goto out;
1330                                 out_ptr += rc;
1331                                 break;
1332                         /* executable */
1333                         case 'e':
1334                                 rc = snprintf(out_ptr, out_end - out_ptr,
1335                                               "%s", current->comm);
1336                                 if (rc > out_end - out_ptr)
1337                                         goto out;
1338                                 out_ptr += rc;
1339                                 break;
1340                         default:
1341                                 break;
1342                         }
1343                         ++pat_ptr;
1344                 }
1345         }
1346         /* Backward compatibility with core_uses_pid:
1347          *
1348          * If core_pattern does not include a %p (as is the default)
1349          * and core_uses_pid is set, then .%pid will be appended to
1350          * the filename */
1351         if (!pid_in_pattern
1352             && (core_uses_pid || atomic_read(&current->mm->mm_users) != 1)) {
1353                 rc = snprintf(out_ptr, out_end - out_ptr,
1354                               ".%d", current->tgid);
1355                 if (rc > out_end - out_ptr)
1356                         goto out;
1357                 out_ptr += rc;
1358         }
1359       out:
1360         *out_ptr = 0;
1361 }
1362
1363 static void zap_threads (struct mm_struct *mm)
1364 {
1365         struct task_struct *g, *p;
1366         struct task_struct *tsk = current;
1367         struct completion *vfork_done = tsk->vfork_done;
1368         int traced = 0;
1369
1370         /*
1371          * Make sure nobody is waiting for us to release the VM,
1372          * otherwise we can deadlock when we wait on each other
1373          */
1374         if (vfork_done) {
1375                 tsk->vfork_done = NULL;
1376                 complete(vfork_done);
1377         }
1378
1379         read_lock(&tasklist_lock);
1380         do_each_thread(g,p)
1381                 if (mm == p->mm && p != tsk) {
1382                         force_sig_specific(SIGKILL, p);
1383                         mm->core_waiters++;
1384                         if (unlikely(p->ptrace) &&
1385                             unlikely(p->parent->mm == mm))
1386                                 traced = 1;
1387                 }
1388         while_each_thread(g,p);
1389
1390         read_unlock(&tasklist_lock);
1391
1392         if (unlikely(traced)) {
1393                 /*
1394                  * We are zapping a thread and the thread it ptraces.
1395                  * If the tracee went into a ptrace stop for exit tracing,
1396                  * we could deadlock since the tracer is waiting for this
1397                  * coredump to finish.  Detach them so they can both die.
1398                  */
1399                 write_lock_irq(&tasklist_lock);
1400                 do_each_thread(g,p) {
1401                         if (mm == p->mm && p != tsk &&
1402                             p->ptrace && p->parent->mm == mm) {
1403                                 __ptrace_unlink(p);
1404                         }
1405                 } while_each_thread(g,p);
1406                 write_unlock_irq(&tasklist_lock);
1407         }
1408 }
1409
1410 static void coredump_wait(struct mm_struct *mm)
1411 {
1412         DECLARE_COMPLETION(startup_done);
1413
1414         mm->core_waiters++; /* let other threads block */
1415         mm->core_startup_done = &startup_done;
1416
1417         /* give other threads a chance to run: */
1418         yield();
1419
1420         zap_threads(mm);
1421         if (--mm->core_waiters) {
1422                 up_write(&mm->mmap_sem);
1423                 wait_for_completion(&startup_done);
1424         } else
1425                 up_write(&mm->mmap_sem);
1426         BUG_ON(mm->core_waiters);
1427 }
1428
1429 int do_coredump(long signr, int exit_code, struct pt_regs * regs)
1430 {
1431         char corename[CORENAME_MAX_SIZE + 1];
1432         struct mm_struct *mm = current->mm;
1433         struct linux_binfmt * binfmt;
1434         struct inode * inode;
1435         struct file * file;
1436         int retval = 0;
1437
1438         binfmt = current->binfmt;
1439         if (!binfmt || !binfmt->core_dump)
1440                 goto fail;
1441         down_write(&mm->mmap_sem);
1442         if (!mm->dumpable) {
1443                 up_write(&mm->mmap_sem);
1444                 goto fail;
1445         }
1446         mm->dumpable = 0;
1447         init_completion(&mm->core_done);
1448         spin_lock_irq(&current->sighand->siglock);
1449         current->signal->flags = SIGNAL_GROUP_EXIT;
1450         current->signal->group_exit_code = exit_code;
1451         spin_unlock_irq(&current->sighand->siglock);
1452         coredump_wait(mm);
1453
1454         /*
1455          * Clear any false indication of pending signals that might
1456          * be seen by the filesystem code called to write the core file.
1457          */
1458         current->signal->group_stop_count = 0;
1459         clear_thread_flag(TIF_SIGPENDING);
1460
1461         if (current->signal->rlim[RLIMIT_CORE].rlim_cur < binfmt->min_coredump)
1462                 goto fail_unlock;
1463
1464         /*
1465          * lock_kernel() because format_corename() is controlled by sysctl, which
1466          * uses lock_kernel()
1467          */
1468         lock_kernel();
1469         format_corename(corename, core_pattern, signr);
1470         unlock_kernel();
1471         file = filp_open(corename, O_CREAT | 2 | O_NOFOLLOW | O_LARGEFILE, 0600);
1472         if (IS_ERR(file))
1473                 goto fail_unlock;
1474         inode = file->f_dentry->d_inode;
1475         if (inode->i_nlink > 1)
1476                 goto close_fail;        /* multiple links - don't dump */
1477         if (d_unhashed(file->f_dentry))
1478                 goto close_fail;
1479
1480         if (!S_ISREG(inode->i_mode))
1481                 goto close_fail;
1482         if (!file->f_op)
1483                 goto close_fail;
1484         if (!file->f_op->write)
1485                 goto close_fail;
1486         if (do_truncate(file->f_dentry, 0) != 0)
1487                 goto close_fail;
1488
1489         retval = binfmt->core_dump(signr, regs, file);
1490
1491         if (retval)
1492                 current->signal->group_exit_code |= 0x80;
1493 close_fail:
1494         filp_close(file, NULL);
1495 fail_unlock:
1496         complete_all(&mm->core_done);
1497 fail:
1498         return retval;
1499 }