Fedora Core 2 - 1.492
[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/mmu_context.h>
52
53 #ifdef CONFIG_KMOD
54 #include <linux/kmod.h>
55 #endif
56
57 int core_uses_pid;
58 char core_pattern[65] = "core";
59 /* The maximal length of core_pattern is also specified in sysctl.c */
60
61 static struct linux_binfmt *formats;
62 static rwlock_t binfmt_lock = RW_LOCK_UNLOCKED;
63
64 int register_binfmt(struct linux_binfmt * fmt)
65 {
66         struct linux_binfmt ** tmp = &formats;
67
68         if (!fmt)
69                 return -EINVAL;
70         if (fmt->next)
71                 return -EBUSY;
72         write_lock(&binfmt_lock);
73         while (*tmp) {
74                 if (fmt == *tmp) {
75                         write_unlock(&binfmt_lock);
76                         return -EBUSY;
77                 }
78                 tmp = &(*tmp)->next;
79         }
80         fmt->next = formats;
81         formats = fmt;
82         write_unlock(&binfmt_lock);
83         return 0;       
84 }
85
86 EXPORT_SYMBOL(register_binfmt);
87
88 int unregister_binfmt(struct linux_binfmt * fmt)
89 {
90         struct linux_binfmt ** tmp = &formats;
91
92         write_lock(&binfmt_lock);
93         while (*tmp) {
94                 if (fmt == *tmp) {
95                         *tmp = fmt->next;
96                         write_unlock(&binfmt_lock);
97                         return 0;
98                 }
99                 tmp = &(*tmp)->next;
100         }
101         write_unlock(&binfmt_lock);
102         return -EINVAL;
103 }
104
105 EXPORT_SYMBOL(unregister_binfmt);
106
107 static inline void put_binfmt(struct linux_binfmt * fmt)
108 {
109         module_put(fmt->module);
110 }
111
112 /*
113  * Note that a shared library must be both readable and executable due to
114  * security reasons.
115  *
116  * Also note that we take the address to load from from the file itself.
117  */
118 asmlinkage long sys_uselib(const char __user * library)
119 {
120         struct file * file;
121         struct nameidata nd;
122         int error;
123
124         nd.intent.open.flags = FMODE_READ;
125         error = __user_walk(library, LOOKUP_FOLLOW|LOOKUP_OPEN, &nd);
126         if (error)
127                 goto out;
128
129         error = -EINVAL;
130         if (!S_ISREG(nd.dentry->d_inode->i_mode))
131                 goto exit;
132
133         error = permission(nd.dentry->d_inode, MAY_READ | MAY_EXEC, &nd);
134         if (error)
135                 goto exit;
136
137         file = dentry_open(nd.dentry, nd.mnt, O_RDONLY);
138         error = PTR_ERR(file);
139         if (IS_ERR(file))
140                 goto out;
141
142         error = -ENOEXEC;
143         if(file->f_op) {
144                 struct linux_binfmt * fmt;
145
146                 read_lock(&binfmt_lock);
147                 for (fmt = formats ; fmt ; fmt = fmt->next) {
148                         if (!fmt->load_shlib)
149                                 continue;
150                         if (!try_module_get(fmt->module))
151                                 continue;
152                         read_unlock(&binfmt_lock);
153                         error = fmt->load_shlib(file);
154                         read_lock(&binfmt_lock);
155                         put_binfmt(fmt);
156                         if (error != -ENOEXEC)
157                                 break;
158                 }
159                 read_unlock(&binfmt_lock);
160         }
161         fput(file);
162 out:
163         return error;
164 exit:
165         path_release(&nd);
166         goto out;
167 }
168
169 /*
170  * count() counts the number of strings in array ARGV.
171  */
172 static int count(char __user * __user * argv, int max)
173 {
174         int i = 0;
175
176         if (argv != NULL) {
177                 for (;;) {
178                         char __user * p;
179
180                         if (get_user(p, argv))
181                                 return -EFAULT;
182                         if (!p)
183                                 break;
184                         argv++;
185                         if(++i > max)
186                                 return -E2BIG;
187                 }
188         }
189         return i;
190 }
191
192 /*
193  * 'copy_strings()' copies argument/environment strings from user
194  * memory to free pages in kernel mem. These are in a format ready
195  * to be put directly into the top of new user memory.
196  */
197 int copy_strings(int argc,char __user * __user * argv, struct linux_binprm *bprm)
198 {
199         struct page *kmapped_page = NULL;
200         char *kaddr = NULL;
201         int ret;
202
203         while (argc-- > 0) {
204                 char __user *str;
205                 int len;
206                 unsigned long pos;
207
208                 if (get_user(str, argv+argc) ||
209                                 !(len = strnlen_user(str, bprm->p))) {
210                         ret = -EFAULT;
211                         goto out;
212                 }
213
214                 if (bprm->p < len)  {
215                         ret = -E2BIG;
216                         goto out;
217                 }
218
219                 bprm->p -= len;
220                 /* XXX: add architecture specific overflow check here. */
221                 pos = bprm->p;
222
223                 while (len > 0) {
224                         int i, new, err;
225                         int offset, bytes_to_copy;
226                         struct page *page;
227
228                         offset = pos % PAGE_SIZE;
229                         i = pos/PAGE_SIZE;
230                         page = bprm->page[i];
231                         new = 0;
232                         if (!page) {
233                                 page = alloc_page(GFP_HIGHUSER);
234                                 bprm->page[i] = page;
235                                 if (!page) {
236                                         ret = -ENOMEM;
237                                         goto out;
238                                 }
239                                 new = 1;
240                         }
241
242                         if (page != kmapped_page) {
243                                 if (kmapped_page)
244                                         kunmap(kmapped_page);
245                                 kmapped_page = page;
246                                 kaddr = kmap(kmapped_page);
247                         }
248                         if (new && offset)
249                                 memset(kaddr, 0, offset);
250                         bytes_to_copy = PAGE_SIZE - offset;
251                         if (bytes_to_copy > len) {
252                                 bytes_to_copy = len;
253                                 if (new)
254                                         memset(kaddr+offset+len, 0,
255                                                 PAGE_SIZE-offset-len);
256                         }
257                         err = copy_from_user(kaddr+offset, str, bytes_to_copy);
258                         if (err) {
259                                 ret = -EFAULT;
260                                 goto out;
261                         }
262
263                         pos += bytes_to_copy;
264                         str += bytes_to_copy;
265                         len -= bytes_to_copy;
266                 }
267         }
268         ret = 0;
269 out:
270         if (kmapped_page)
271                 kunmap(kmapped_page);
272         return ret;
273 }
274
275 /*
276  * Like copy_strings, but get argv and its values from kernel memory.
277  */
278 int copy_strings_kernel(int argc,char ** argv, struct linux_binprm *bprm)
279 {
280         int r;
281         mm_segment_t oldfs = get_fs();
282         set_fs(KERNEL_DS);
283         r = copy_strings(argc, (char __user * __user *)argv, bprm);
284         set_fs(oldfs);
285         return r;
286 }
287
288 EXPORT_SYMBOL(copy_strings_kernel);
289
290 #ifdef CONFIG_MMU
291 /*
292  * This routine is used to map in a page into an address space: needed by
293  * execve() for the initial stack and environment pages.
294  *
295  * vma->vm_mm->mmap_sem is held for writing.
296  */
297 void install_arg_page(struct vm_area_struct *vma,
298                         struct page *page, unsigned long address)
299 {
300         struct mm_struct *mm = vma->vm_mm;
301         pgd_t * pgd;
302         pmd_t * pmd;
303         pte_t * pte;
304
305         if (unlikely(anon_vma_prepare(vma)))
306                 goto out_sig;
307
308         flush_dcache_page(page);
309         pgd = pgd_offset(mm, address);
310
311         spin_lock(&mm->page_table_lock);
312         pmd = pmd_alloc(mm, pgd, address);
313         if (!pmd)
314                 goto out;
315         pte = pte_alloc_map(mm, pmd, address);
316         if (!pte)
317                 goto out;
318         if (!pte_none(*pte)) {
319                 pte_unmap(pte);
320                 goto out;
321         }
322         mm->rss++;
323         lru_cache_add_active(page);
324         set_pte(pte, pte_mkdirty(pte_mkwrite(mk_pte(
325                                         page, vma->vm_page_prot))));
326         page_add_anon_rmap(page, vma, address);
327         pte_unmap(pte);
328         spin_unlock(&mm->page_table_lock);
329
330         /* no need for flush_tlb */
331         return;
332 out:
333         spin_unlock(&mm->page_table_lock);
334 out_sig:
335         __free_page(page);
336         force_sig(SIGKILL, current);
337 }
338
339 int setup_arg_pages(struct linux_binprm *bprm, int executable_stack)
340 {
341         unsigned long stack_base;
342         struct vm_area_struct *mpnt;
343         struct mm_struct *mm = current->mm;
344         int i;
345         long arg_size;
346
347 #ifdef CONFIG_STACK_GROWSUP
348         /* Move the argument and environment strings to the bottom of the
349          * stack space.
350          */
351         int offset, j;
352         char *to, *from;
353
354         /* Start by shifting all the pages down */
355         i = 0;
356         for (j = 0; j < MAX_ARG_PAGES; j++) {
357                 struct page *page = bprm->page[j];
358                 if (!page)
359                         continue;
360                 bprm->page[i++] = page;
361         }
362
363         /* Now move them within their pages */
364         offset = bprm->p % PAGE_SIZE;
365         to = kmap(bprm->page[0]);
366         for (j = 1; j < i; j++) {
367                 memmove(to, to + offset, PAGE_SIZE - offset);
368                 from = kmap(bprm->page[j]);
369                 memcpy(to + PAGE_SIZE - offset, from, offset);
370                 kunmap(bprm->page[j - 1]);
371                 to = from;
372         }
373         memmove(to, to + offset, PAGE_SIZE - offset);
374         kunmap(bprm->page[j - 1]);
375
376         /* Adjust bprm->p to point to the end of the strings. */
377         bprm->p = PAGE_SIZE * i - offset;
378
379         /* Limit stack size to 1GB */
380         stack_base = current->rlim[RLIMIT_STACK].rlim_max;
381         if (stack_base > (1 << 30))
382                 stack_base = 1 << 30;
383         stack_base = PAGE_ALIGN(STACK_TOP - stack_base);
384
385         mm->arg_start = stack_base;
386         arg_size = i << PAGE_SHIFT;
387
388         /* zero pages that were copied above */
389         while (i < MAX_ARG_PAGES)
390                 bprm->page[i++] = NULL;
391 #else
392 #ifdef __HAVE_ARCH_ALIGN_STACK
393         stack_base = arch_align_stack(STACK_TOP - MAX_ARG_PAGES*PAGE_SIZE);
394         stack_base = PAGE_ALIGN(stack_base);
395 #else
396         stack_base = STACK_TOP - MAX_ARG_PAGES * PAGE_SIZE;
397 #endif
398         mm->arg_start = bprm->p + stack_base;
399         arg_size = STACK_TOP - (PAGE_MASK & (unsigned long) mm->arg_start);
400 #endif
401
402         bprm->p += stack_base;
403         if (bprm->loader)
404                 bprm->loader += stack_base;
405         bprm->exec += stack_base;
406
407         mpnt = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
408         if (!mpnt)
409                 return -ENOMEM;
410
411         if (security_vm_enough_memory(arg_size >> PAGE_SHIFT)) {
412                 kmem_cache_free(vm_area_cachep, mpnt);
413                 return -ENOMEM;
414         }
415
416         memset(mpnt, 0, sizeof(*mpnt));
417
418         down_write(&mm->mmap_sem);
419         {
420                 mpnt->vm_mm = mm;
421 #ifdef CONFIG_STACK_GROWSUP
422                 mpnt->vm_start = stack_base;
423                 mpnt->vm_end = PAGE_MASK &
424                         (PAGE_SIZE - 1 + (unsigned long) bprm->p);
425 #else
426                 mpnt->vm_start = PAGE_MASK & (unsigned long) bprm->p;
427                 mpnt->vm_end = STACK_TOP;
428 #endif
429                 /* Adjust stack execute permissions; explicitly enable
430                  * for EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X
431                  * and leave alone (arch default) otherwise. */
432                 if (unlikely(executable_stack == EXSTACK_ENABLE_X))
433                         mpnt->vm_flags = VM_STACK_FLAGS |  VM_EXEC;
434                 else if (executable_stack == EXSTACK_DISABLE_X)
435                         mpnt->vm_flags = VM_STACK_FLAGS & ~VM_EXEC;
436                 else
437                         mpnt->vm_flags = VM_STACK_FLAGS;
438                 mpnt->vm_flags |= mm->def_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             (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP))
850                 current->mm->dumpable = 0;
851
852         /* An exec changes our domain. We are no longer part of the thread
853            group */
854
855         current->self_exec_id++;
856                         
857         flush_signal_handlers(current, 0);
858         flush_old_files(current->files);
859
860         return 0;
861
862 mmap_failed:
863         put_files_struct(current->files);
864         current->files = files;
865 out:
866         return retval;
867 }
868
869 EXPORT_SYMBOL(flush_old_exec);
870
871 /* 
872  * Fill the binprm structure from the inode. 
873  * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
874  */
875 int prepare_binprm(struct linux_binprm *bprm)
876 {
877         int mode;
878         struct inode * inode = bprm->file->f_dentry->d_inode;
879         int retval;
880
881         mode = inode->i_mode;
882         /*
883          * Check execute perms again - if the caller has CAP_DAC_OVERRIDE,
884          * vfs_permission lets a non-executable through
885          */
886         if (!(mode & 0111))     /* with at least _one_ execute bit set */
887                 return -EACCES;
888         if (bprm->file->f_op == NULL)
889                 return -EACCES;
890
891         bprm->e_uid = current->euid;
892         bprm->e_gid = current->egid;
893
894         if(!(bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)) {
895                 /* Set-uid? */
896                 if (mode & S_ISUID) {
897                         bprm->e_uid = inode->i_uid;
898 #ifdef __i386__
899                         /* reset personality */
900                         current->personality = PER_LINUX;
901 #endif
902                 }
903
904                 /* Set-gid? */
905                 /*
906                  * If setgid is set but no group execute bit then this
907                  * is a candidate for mandatory locking, not a setgid
908                  * executable.
909                  */
910                 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
911                         bprm->e_gid = inode->i_gid;
912 #ifdef __i386__
913                         /* reset personality */
914                         current->personality = PER_LINUX;
915 #endif
916                 }
917         }
918
919         /* fill in binprm security blob */
920         retval = security_bprm_set(bprm);
921         if (retval)
922                 return retval;
923
924         memset(bprm->buf,0,BINPRM_BUF_SIZE);
925         return kernel_read(bprm->file,0,bprm->buf,BINPRM_BUF_SIZE);
926 }
927
928 EXPORT_SYMBOL(prepare_binprm);
929
930 static inline int unsafe_exec(struct task_struct *p)
931 {
932         int unsafe = 0;
933         if (p->ptrace & PT_PTRACED) {
934                 if (p->ptrace & PT_PTRACE_CAP)
935                         unsafe |= LSM_UNSAFE_PTRACE_CAP;
936                 else
937                         unsafe |= LSM_UNSAFE_PTRACE;
938         }
939         if (atomic_read(&p->fs->count) > 1 ||
940             atomic_read(&p->files->count) > 1 ||
941             atomic_read(&p->sighand->count) > 1)
942                 unsafe |= LSM_UNSAFE_SHARE;
943
944         return unsafe;
945 }
946
947 void compute_creds(struct linux_binprm *bprm)
948 {
949         int unsafe;
950         task_lock(current);
951         unsafe = unsafe_exec(current);
952         security_bprm_apply_creds(bprm, unsafe);
953         task_unlock(current);
954 }
955
956 EXPORT_SYMBOL(compute_creds);
957
958 void remove_arg_zero(struct linux_binprm *bprm)
959 {
960         if (bprm->argc) {
961                 unsigned long offset;
962                 char * kaddr;
963                 struct page *page;
964
965                 offset = bprm->p % PAGE_SIZE;
966                 goto inside;
967
968                 while (bprm->p++, *(kaddr+offset++)) {
969                         if (offset != PAGE_SIZE)
970                                 continue;
971                         offset = 0;
972                         kunmap_atomic(kaddr, KM_USER0);
973 inside:
974                         page = bprm->page[bprm->p/PAGE_SIZE];
975                         kaddr = kmap_atomic(page, KM_USER0);
976                 }
977                 kunmap_atomic(kaddr, KM_USER0);
978                 bprm->argc--;
979         }
980 }
981
982 EXPORT_SYMBOL(remove_arg_zero);
983
984 /*
985  * cycle the list of binary formats handler, until one recognizes the image
986  */
987 int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs)
988 {
989         int try,retval=0;
990         struct linux_binfmt *fmt;
991 #ifdef __alpha__
992         /* handle /sbin/loader.. */
993         {
994             struct exec * eh = (struct exec *) bprm->buf;
995
996             if (!bprm->loader && eh->fh.f_magic == 0x183 &&
997                 (eh->fh.f_flags & 0x3000) == 0x3000)
998             {
999                 struct file * file;
1000                 unsigned long loader;
1001
1002                 allow_write_access(bprm->file);
1003                 fput(bprm->file);
1004                 bprm->file = NULL;
1005
1006                 loader = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1007
1008                 file = open_exec("/sbin/loader");
1009                 retval = PTR_ERR(file);
1010                 if (IS_ERR(file))
1011                         return retval;
1012
1013                 /* Remember if the application is TASO.  */
1014                 bprm->sh_bang = eh->ah.entry < 0x100000000UL;
1015
1016                 bprm->file = file;
1017                 bprm->loader = loader;
1018                 retval = prepare_binprm(bprm);
1019                 if (retval<0)
1020                         return retval;
1021                 /* should call search_binary_handler recursively here,
1022                    but it does not matter */
1023             }
1024         }
1025 #endif
1026         retval = security_bprm_check(bprm);
1027         if (retval)
1028                 return retval;
1029
1030         /* kernel module loader fixup */
1031         /* so we don't try to load run modprobe in kernel space. */
1032         set_fs(USER_DS);
1033         for (try=0; try<2; try++) {
1034                 read_lock(&binfmt_lock);
1035                 for (fmt = formats ; fmt ; fmt = fmt->next) {
1036                         int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
1037                         if (!fn)
1038                                 continue;
1039                         if (!try_module_get(fmt->module))
1040                                 continue;
1041                         read_unlock(&binfmt_lock);
1042                         retval = fn(bprm, regs);
1043                         if (retval >= 0) {
1044                                 put_binfmt(fmt);
1045                                 allow_write_access(bprm->file);
1046                                 if (bprm->file)
1047                                         fput(bprm->file);
1048                                 bprm->file = NULL;
1049                                 current->did_exec = 1;
1050                                 return retval;
1051                         }
1052                         read_lock(&binfmt_lock);
1053                         put_binfmt(fmt);
1054                         if (retval != -ENOEXEC || bprm->mm == NULL)
1055                                 break;
1056                         if (!bprm->file) {
1057                                 read_unlock(&binfmt_lock);
1058                                 return retval;
1059                         }
1060                 }
1061                 read_unlock(&binfmt_lock);
1062                 if (retval != -ENOEXEC || bprm->mm == NULL) {
1063                         break;
1064 #ifdef CONFIG_KMOD
1065                 }else{
1066 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
1067                         if (printable(bprm->buf[0]) &&
1068                             printable(bprm->buf[1]) &&
1069                             printable(bprm->buf[2]) &&
1070                             printable(bprm->buf[3]))
1071                                 break; /* -ENOEXEC */
1072                         request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
1073 #endif
1074                 }
1075         }
1076         return retval;
1077 }
1078
1079 EXPORT_SYMBOL(search_binary_handler);
1080
1081 /*
1082  * sys_execve() executes a new program.
1083  */
1084 int do_execve(char * filename,
1085         char __user *__user *argv,
1086         char __user *__user *envp,
1087         struct pt_regs * regs)
1088 {
1089         struct linux_binprm bprm;
1090         struct file *file;
1091         int retval;
1092         int i;
1093
1094         file = open_exec(filename);
1095
1096         retval = PTR_ERR(file);
1097         if (IS_ERR(file))
1098                 return retval;
1099
1100         sched_balance_exec();
1101
1102         bprm.p = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1103         memset(bprm.page, 0, MAX_ARG_PAGES*sizeof(bprm.page[0]));
1104
1105         bprm.file = file;
1106         bprm.filename = filename;
1107         bprm.interp = filename;
1108         bprm.interp_flags = 0;
1109         bprm.interp_data = 0;
1110         bprm.sh_bang = 0;
1111         bprm.loader = 0;
1112         bprm.exec = 0;
1113         bprm.security = NULL;
1114         bprm.mm = mm_alloc();
1115         retval = -ENOMEM;
1116         if (!bprm.mm)
1117                 goto out_file;
1118
1119         retval = init_new_context(current, bprm.mm);
1120         if (retval < 0)
1121                 goto out_mm;
1122
1123         bprm.argc = count(argv, bprm.p / sizeof(void *));
1124         if ((retval = bprm.argc) < 0)
1125                 goto out_mm;
1126
1127         bprm.envc = count(envp, bprm.p / sizeof(void *));
1128         if ((retval = bprm.envc) < 0)
1129                 goto out_mm;
1130
1131         retval = security_bprm_alloc(&bprm);
1132         if (retval)
1133                 goto out;
1134
1135         retval = prepare_binprm(&bprm);
1136         if (retval < 0)
1137                 goto out;
1138
1139         retval = copy_strings_kernel(1, &bprm.filename, &bprm);
1140         if (retval < 0)
1141                 goto out;
1142
1143         bprm.exec = bprm.p;
1144         retval = copy_strings(bprm.envc, envp, &bprm);
1145         if (retval < 0)
1146                 goto out;
1147
1148         retval = copy_strings(bprm.argc, argv, &bprm);
1149         if (retval < 0)
1150                 goto out;
1151
1152         retval = search_binary_handler(&bprm,regs);
1153         if (retval >= 0) {
1154                 free_arg_pages(&bprm);
1155
1156                 /* execve success */
1157                 security_bprm_free(&bprm);
1158                 return retval;
1159         }
1160
1161 out:
1162         /* Something went wrong, return the inode and free the argument pages*/
1163         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
1164                 struct page * page = bprm.page[i];
1165                 if (page)
1166                         __free_page(page);
1167         }
1168
1169         if (bprm.security)
1170                 security_bprm_free(&bprm);
1171
1172 out_mm:
1173         if (bprm.mm)
1174                 mmdrop(bprm.mm);
1175
1176 out_file:
1177         if (bprm.file) {
1178                 allow_write_access(bprm.file);
1179                 fput(bprm.file);
1180         }
1181         return retval;
1182 }
1183
1184 EXPORT_SYMBOL(do_execve);
1185
1186 int set_binfmt(struct linux_binfmt *new)
1187 {
1188         struct linux_binfmt *old = current->binfmt;
1189
1190         if (new) {
1191                 if (!try_module_get(new->module))
1192                         return -1;
1193         }
1194         current->binfmt = new;
1195         if (old)
1196                 module_put(old->module);
1197         return 0;
1198 }
1199
1200 EXPORT_SYMBOL(set_binfmt);
1201
1202 #define CORENAME_MAX_SIZE 64
1203
1204 /* format_corename will inspect the pattern parameter, and output a
1205  * name into corename, which must have space for at least
1206  * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
1207  */
1208 void format_corename(char *corename, const char *pattern, long signr)
1209 {
1210         const char *pat_ptr = pattern;
1211         char *out_ptr = corename;
1212         char *const out_end = corename + CORENAME_MAX_SIZE;
1213         int rc;
1214         int pid_in_pattern = 0;
1215
1216         /* Repeat as long as we have more pattern to process and more output
1217            space */
1218         while (*pat_ptr) {
1219                 if (*pat_ptr != '%') {
1220                         if (out_ptr == out_end)
1221                                 goto out;
1222                         *out_ptr++ = *pat_ptr++;
1223                 } else {
1224                         switch (*++pat_ptr) {
1225                         case 0:
1226                                 goto out;
1227                         /* Double percent, output one percent */
1228                         case '%':
1229                                 if (out_ptr == out_end)
1230                                         goto out;
1231                                 *out_ptr++ = '%';
1232                                 break;
1233                         /* pid */
1234                         case 'p':
1235                                 pid_in_pattern = 1;
1236                                 rc = snprintf(out_ptr, out_end - out_ptr,
1237                                               "%d", current->tgid);
1238                                 if (rc > out_end - out_ptr)
1239                                         goto out;
1240                                 out_ptr += rc;
1241                                 break;
1242                         /* uid */
1243                         case 'u':
1244                                 rc = snprintf(out_ptr, out_end - out_ptr,
1245                                               "%d", current->uid);
1246                                 if (rc > out_end - out_ptr)
1247                                         goto out;
1248                                 out_ptr += rc;
1249                                 break;
1250                         /* gid */
1251                         case 'g':
1252                                 rc = snprintf(out_ptr, out_end - out_ptr,
1253                                               "%d", current->gid);
1254                                 if (rc > out_end - out_ptr)
1255                                         goto out;
1256                                 out_ptr += rc;
1257                                 break;
1258                         /* signal that caused the coredump */
1259                         case 's':
1260                                 rc = snprintf(out_ptr, out_end - out_ptr,
1261                                               "%ld", signr);
1262                                 if (rc > out_end - out_ptr)
1263                                         goto out;
1264                                 out_ptr += rc;
1265                                 break;
1266                         /* UNIX time of coredump */
1267                         case 't': {
1268                                 struct timeval tv;
1269                                 do_gettimeofday(&tv);
1270                                 rc = snprintf(out_ptr, out_end - out_ptr,
1271                                               "%lu", tv.tv_sec);
1272                                 if (rc > out_end - out_ptr)
1273                                         goto out;
1274                                 out_ptr += rc;
1275                                 break;
1276                         }
1277                         /* hostname */
1278                         case 'h':
1279                                 down_read(&uts_sem);
1280                                 rc = snprintf(out_ptr, out_end - out_ptr,
1281                                               "%s", system_utsname.nodename);
1282                                 up_read(&uts_sem);
1283                                 if (rc > out_end - out_ptr)
1284                                         goto out;
1285                                 out_ptr += rc;
1286                                 break;
1287                         /* executable */
1288                         case 'e':
1289                                 rc = snprintf(out_ptr, out_end - out_ptr,
1290                                               "%s", current->comm);
1291                                 if (rc > out_end - out_ptr)
1292                                         goto out;
1293                                 out_ptr += rc;
1294                                 break;
1295                         default:
1296                                 break;
1297                         }
1298                         ++pat_ptr;
1299                 }
1300         }
1301         /* Backward compatibility with core_uses_pid:
1302          *
1303          * If core_pattern does not include a %p (as is the default)
1304          * and core_uses_pid is set, then .%pid will be appended to
1305          * the filename */
1306         if (!pid_in_pattern
1307             && (core_uses_pid || atomic_read(&current->mm->mm_users) != 1)) {
1308                 rc = snprintf(out_ptr, out_end - out_ptr,
1309                               ".%d", current->tgid);
1310                 if (rc > out_end - out_ptr)
1311                         goto out;
1312                 out_ptr += rc;
1313         }
1314       out:
1315         *out_ptr = 0;
1316 }
1317
1318 static void zap_threads (struct mm_struct *mm)
1319 {
1320         struct task_struct *g, *p;
1321         struct task_struct *tsk = current;
1322         struct completion *vfork_done = tsk->vfork_done;
1323
1324         /*
1325          * Make sure nobody is waiting for us to release the VM,
1326          * otherwise we can deadlock when we wait on each other
1327          */
1328         if (vfork_done) {
1329                 tsk->vfork_done = NULL;
1330                 complete(vfork_done);
1331         }
1332
1333         read_lock(&tasklist_lock);
1334         do_each_thread(g,p)
1335                 if (mm == p->mm && p != tsk) {
1336                         force_sig_specific(SIGKILL, p);
1337                         mm->core_waiters++;
1338                 }
1339         while_each_thread(g,p);
1340
1341         read_unlock(&tasklist_lock);
1342 }
1343
1344 static void coredump_wait(struct mm_struct *mm)
1345 {
1346         DECLARE_COMPLETION(startup_done);
1347
1348         mm->core_waiters++; /* let other threads block */
1349         mm->core_startup_done = &startup_done;
1350
1351         /* give other threads a chance to run: */
1352         yield();
1353
1354         zap_threads(mm);
1355         if (--mm->core_waiters) {
1356                 up_write(&mm->mmap_sem);
1357                 wait_for_completion(&startup_done);
1358         } else
1359                 up_write(&mm->mmap_sem);
1360         BUG_ON(mm->core_waiters);
1361 }
1362
1363 int do_coredump(long signr, int exit_code, struct pt_regs * regs)
1364 {
1365         char corename[CORENAME_MAX_SIZE + 1];
1366         struct mm_struct *mm = current->mm;
1367         struct linux_binfmt * binfmt;
1368         struct inode * inode;
1369         struct file * file;
1370         int retval = 0;
1371
1372         lock_kernel();
1373         binfmt = current->binfmt;
1374         if (!binfmt || !binfmt->core_dump)
1375                 goto fail;
1376         down_write(&mm->mmap_sem);
1377         if (!mm->dumpable) {
1378                 up_write(&mm->mmap_sem);
1379                 goto fail;
1380         }
1381         mm->dumpable = 0;
1382         init_completion(&mm->core_done);
1383         current->signal->group_exit = 1;
1384         current->signal->group_exit_code = exit_code;
1385         coredump_wait(mm);
1386
1387         if (current->rlim[RLIMIT_CORE].rlim_cur < binfmt->min_coredump)
1388                 goto fail_unlock;
1389
1390         format_corename(corename, core_pattern, signr);
1391         file = filp_open(corename, O_CREAT | 2 | O_NOFOLLOW | O_LARGEFILE, 0600);
1392         if (IS_ERR(file))
1393                 goto fail_unlock;
1394         inode = file->f_dentry->d_inode;
1395         if (inode->i_nlink > 1)
1396                 goto close_fail;        /* multiple links - don't dump */
1397         if (d_unhashed(file->f_dentry))
1398                 goto close_fail;
1399
1400         if (!S_ISREG(inode->i_mode))
1401                 goto close_fail;
1402         if (!file->f_op)
1403                 goto close_fail;
1404         if (!file->f_op->write)
1405                 goto close_fail;
1406         if (do_truncate(file->f_dentry, 0) != 0)
1407                 goto close_fail;
1408
1409         retval = binfmt->core_dump(signr, regs, file);
1410
1411         current->signal->group_exit_code |= 0x80;
1412 close_fail:
1413         filp_close(file, NULL);
1414 fail_unlock:
1415         complete_all(&mm->core_done);
1416 fail:
1417         unlock_kernel();
1418         return retval;
1419 }