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