Merge to Fedora Core 2 kernel-2.6.8-1.521
[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 #include <linux/ckrm.h>
50
51 #include <asm/uaccess.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         vx_rsspages_inc(mm);
325         lru_cache_add_active(page);
326         set_pte(pte, pte_mkdirty(pte_mkwrite(mk_pte(
327                                         page, vma->vm_page_prot))));
328         page_add_anon_rmap(page, vma, address);
329         pte_unmap(pte);
330         spin_unlock(&mm->page_table_lock);
331
332         /* no need for flush_tlb */
333         return;
334 out:
335         spin_unlock(&mm->page_table_lock);
336 out_sig:
337         __free_page(page);
338         force_sig(SIGKILL, current);
339 }
340
341 int setup_arg_pages(struct linux_binprm *bprm, int executable_stack)
342 {
343         unsigned long stack_base;
344         struct vm_area_struct *mpnt;
345         struct mm_struct *mm = current->mm;
346         int i;
347         long arg_size;
348
349 #ifdef CONFIG_STACK_GROWSUP
350         /* Move the argument and environment strings to the bottom of the
351          * stack space.
352          */
353         int offset, j;
354         char *to, *from;
355
356         /* Start by shifting all the pages down */
357         i = 0;
358         for (j = 0; j < MAX_ARG_PAGES; j++) {
359                 struct page *page = bprm->page[j];
360                 if (!page)
361                         continue;
362                 bprm->page[i++] = page;
363         }
364
365         /* Now move them within their pages */
366         offset = bprm->p % PAGE_SIZE;
367         to = kmap(bprm->page[0]);
368         for (j = 1; j < i; j++) {
369                 memmove(to, to + offset, PAGE_SIZE - offset);
370                 from = kmap(bprm->page[j]);
371                 memcpy(to + PAGE_SIZE - offset, from, offset);
372                 kunmap(bprm->page[j - 1]);
373                 to = from;
374         }
375         memmove(to, to + offset, PAGE_SIZE - offset);
376         kunmap(bprm->page[j - 1]);
377
378         /* Adjust bprm->p to point to the end of the strings. */
379         bprm->p = PAGE_SIZE * i - offset;
380
381         /* Limit stack size to 1GB */
382         stack_base = current->rlim[RLIMIT_STACK].rlim_max;
383         if (stack_base > (1 << 30))
384                 stack_base = 1 << 30;
385         stack_base = PAGE_ALIGN(STACK_TOP - stack_base);
386
387         mm->arg_start = stack_base;
388         arg_size = i << PAGE_SHIFT;
389
390         /* zero pages that were copied above */
391         while (i < MAX_ARG_PAGES)
392                 bprm->page[i++] = NULL;
393 #else
394 #ifdef __HAVE_ARCH_ALIGN_STACK
395         stack_base = arch_align_stack(STACK_TOP - MAX_ARG_PAGES*PAGE_SIZE);
396         stack_base = PAGE_ALIGN(stack_base);
397 #else
398         stack_base = STACK_TOP - MAX_ARG_PAGES * PAGE_SIZE;
399 #endif
400         mm->arg_start = bprm->p + stack_base;
401         arg_size = STACK_TOP - (PAGE_MASK & (unsigned long) mm->arg_start);
402 #endif
403
404         bprm->p += stack_base;
405         if (bprm->loader)
406                 bprm->loader += stack_base;
407         bprm->exec += stack_base;
408
409         mpnt = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
410         if (!mpnt)
411                 return -ENOMEM;
412
413         if (security_vm_enough_memory(arg_size >> PAGE_SHIFT) ||
414                 !vx_vmpages_avail(mm, arg_size >> PAGE_SHIFT)) {
415                 kmem_cache_free(vm_area_cachep, mpnt);
416                 return -ENOMEM;
417         }
418
419         memset(mpnt, 0, sizeof(*mpnt));
420
421         down_write(&mm->mmap_sem);
422         {
423                 mpnt->vm_mm = mm;
424 #ifdef CONFIG_STACK_GROWSUP
425                 mpnt->vm_start = stack_base;
426                 mpnt->vm_end = PAGE_MASK &
427                         (PAGE_SIZE - 1 + (unsigned long) bprm->p);
428 #else
429                 mpnt->vm_start = PAGE_MASK & (unsigned long) bprm->p;
430                 mpnt->vm_end = STACK_TOP;
431 #endif
432                 /* Adjust stack execute permissions; explicitly enable
433                  * for EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X
434                  * and leave alone (arch default) otherwise. */
435                 if (unlikely(executable_stack == EXSTACK_ENABLE_X))
436                         mpnt->vm_flags = VM_STACK_FLAGS |  VM_EXEC;
437                 else if (executable_stack == EXSTACK_DISABLE_X)
438                         mpnt->vm_flags = VM_STACK_FLAGS & ~VM_EXEC;
439                 else
440                         mpnt->vm_flags = VM_STACK_FLAGS;
441                 mpnt->vm_flags |= mm->def_flags;
442                 mpnt->vm_page_prot = protection_map[mpnt->vm_flags & 0x7];
443                 insert_vm_struct(mm, mpnt);
444                 // mm->total_vm = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT;
445                 vx_vmpages_sub(mm, mm->total_vm -
446                         ((mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT));
447         }
448
449         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
450                 struct page *page = bprm->page[i];
451                 if (page) {
452                         bprm->page[i] = NULL;
453                         install_arg_page(mpnt, page, stack_base);
454                 }
455                 stack_base += PAGE_SIZE;
456         }
457         up_write(&mm->mmap_sem);
458         
459         return 0;
460 }
461
462 EXPORT_SYMBOL(setup_arg_pages);
463
464 #define free_arg_pages(bprm) do { } while (0)
465
466 #else
467
468 static inline void free_arg_pages(struct linux_binprm *bprm)
469 {
470         int i;
471
472         for (i = 0; i < MAX_ARG_PAGES; i++) {
473                 if (bprm->page[i])
474                         __free_page(bprm->page[i]);
475                 bprm->page[i] = NULL;
476         }
477 }
478
479 #endif /* CONFIG_MMU */
480
481 struct file *open_exec(const char *name)
482 {
483         struct nameidata nd;
484         int err;
485         struct file *file;
486
487         nd.intent.open.flags = FMODE_READ;
488         err = path_lookup(name, LOOKUP_FOLLOW|LOOKUP_OPEN, &nd);
489         file = ERR_PTR(err);
490
491         if (!err) {
492                 struct inode *inode = nd.dentry->d_inode;
493                 file = ERR_PTR(-EACCES);
494                 if (!(nd.mnt->mnt_flags & MNT_NOEXEC) &&
495                     S_ISREG(inode->i_mode)) {
496                         int err = permission(inode, MAY_EXEC, &nd);
497                         if (!err && !(inode->i_mode & 0111))
498                                 err = -EACCES;
499                         file = ERR_PTR(err);
500                         if (!err) {
501                                 file = dentry_open(nd.dentry, nd.mnt, O_RDONLY);
502                                 if (!IS_ERR(file)) {
503                                         err = deny_write_access(file);
504                                         if (err) {
505                                                 fput(file);
506                                                 file = ERR_PTR(err);
507                                         }
508                                 }
509 out:
510                                 return file;
511                         }
512                 }
513                 path_release(&nd);
514         }
515         goto out;
516 }
517
518 EXPORT_SYMBOL(open_exec);
519
520 int kernel_read(struct file *file, unsigned long offset,
521         char *addr, unsigned long count)
522 {
523         mm_segment_t old_fs;
524         loff_t pos = offset;
525         int result;
526
527         old_fs = get_fs();
528         set_fs(get_ds());
529         /* The cast to a user pointer is valid due to the set_fs() */
530         result = vfs_read(file, (void __user *)addr, count, &pos);
531         set_fs(old_fs);
532         return result;
533 }
534
535 EXPORT_SYMBOL(kernel_read);
536
537 static int exec_mmap(struct mm_struct *mm)
538 {
539         struct task_struct *tsk;
540         struct mm_struct * old_mm, *active_mm;
541
542         /* Add it to the list of mm's */
543         spin_lock(&mmlist_lock);
544         list_add(&mm->mmlist, &init_mm.mmlist);
545         mmlist_nr++;
546         spin_unlock(&mmlist_lock);
547
548         /* Notify parent that we're no longer interested in the old VM */
549         tsk = current;
550         old_mm = current->mm;
551         mm_release(tsk, old_mm);
552
553         task_lock(tsk);
554         active_mm = tsk->active_mm;
555         tsk->mm = mm;
556         tsk->active_mm = mm;
557         activate_mm(active_mm, mm);
558         task_unlock(tsk);
559         arch_pick_mmap_layout(mm);
560         if (old_mm) {
561                 if (active_mm != old_mm) BUG();
562                 mmput(old_mm);
563                 return 0;
564         }
565         mmdrop(active_mm);
566         return 0;
567 }
568
569 /*
570  * This function makes sure the current process has its own signal table,
571  * so that flush_signal_handlers can later reset the handlers without
572  * disturbing other processes.  (Other processes might share the signal
573  * table via the CLONE_SIGHAND option to clone().)
574  */
575 static inline int de_thread(struct task_struct *tsk)
576 {
577         struct signal_struct *newsig, *oldsig = tsk->signal;
578         struct sighand_struct *newsighand, *oldsighand = tsk->sighand;
579         spinlock_t *lock = &oldsighand->siglock;
580         int count;
581
582         /*
583          * If we don't share sighandlers, then we aren't sharing anything
584          * and we can just re-use it all.
585          */
586         if (atomic_read(&oldsighand->count) <= 1)
587                 return 0;
588
589         newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
590         if (!newsighand)
591                 return -ENOMEM;
592
593         spin_lock_init(&newsighand->siglock);
594         atomic_set(&newsighand->count, 1);
595         memcpy(newsighand->action, oldsighand->action, sizeof(newsighand->action));
596
597         /*
598          * See if we need to allocate a new signal structure
599          */
600         newsig = NULL;
601         if (atomic_read(&oldsig->count) > 1) {
602                 newsig = kmem_cache_alloc(signal_cachep, GFP_KERNEL);
603                 if (!newsig) {
604                         kmem_cache_free(sighand_cachep, newsighand);
605                         return -ENOMEM;
606                 }
607                 atomic_set(&newsig->count, 1);
608                 newsig->group_exit = 0;
609                 newsig->group_exit_code = 0;
610                 newsig->group_exit_task = NULL;
611                 newsig->group_stop_count = 0;
612                 newsig->curr_target = NULL;
613                 init_sigpending(&newsig->shared_pending);
614                 INIT_LIST_HEAD(&newsig->posix_timers);
615
616                 newsig->tty = oldsig->tty;
617                 newsig->pgrp = oldsig->pgrp;
618                 newsig->session = oldsig->session;
619                 newsig->leader = oldsig->leader;
620                 newsig->tty_old_pgrp = oldsig->tty_old_pgrp;
621         }
622
623         if (thread_group_empty(current))
624                 goto no_thread_group;
625
626         /*
627          * Kill all other threads in the thread group.
628          * We must hold tasklist_lock to call zap_other_threads.
629          */
630         read_lock(&tasklist_lock);
631         spin_lock_irq(lock);
632         if (oldsig->group_exit) {
633                 /*
634                  * Another group action in progress, just
635                  * return so that the signal is processed.
636                  */
637                 spin_unlock_irq(lock);
638                 read_unlock(&tasklist_lock);
639                 kmem_cache_free(sighand_cachep, newsighand);
640                 if (newsig)
641                         kmem_cache_free(signal_cachep, newsig);
642                 return -EAGAIN;
643         }
644         oldsig->group_exit = 1;
645         zap_other_threads(current);
646         read_unlock(&tasklist_lock);
647
648         /*
649          * Account for the thread group leader hanging around:
650          */
651         count = 2;
652         if (current->pid == current->tgid)
653                 count = 1;
654         while (atomic_read(&oldsig->count) > count) {
655                 oldsig->group_exit_task = current;
656                 oldsig->notify_count = count;
657                 __set_current_state(TASK_UNINTERRUPTIBLE);
658                 spin_unlock_irq(lock);
659                 schedule();
660                 spin_lock_irq(lock);
661         }
662         spin_unlock_irq(lock);
663
664         /*
665          * At this point all other threads have exited, all we have to
666          * do is to wait for the thread group leader to become inactive,
667          * and to assume its PID:
668          */
669         if (current->pid != current->tgid) {
670                 struct task_struct *leader = current->group_leader, *parent;
671                 struct dentry *proc_dentry1, *proc_dentry2;
672                 unsigned long state, ptrace;
673
674                 /*
675                  * Wait for the thread group leader to be a zombie.
676                  * It should already be zombie at this point, most
677                  * of the time.
678                  */
679                 while (leader->state != TASK_ZOMBIE)
680                         yield();
681
682                 spin_lock(&leader->proc_lock);
683                 spin_lock(&current->proc_lock);
684                 proc_dentry1 = proc_pid_unhash(current);
685                 proc_dentry2 = proc_pid_unhash(leader);
686                 write_lock_irq(&tasklist_lock);
687
688                 if (leader->tgid != current->tgid)
689                         BUG();
690                 if (current->pid == current->tgid)
691                         BUG();
692                 /*
693                  * An exec() starts a new thread group with the
694                  * TGID of the previous thread group. Rehash the
695                  * two threads with a switched PID, and release
696                  * the former thread group leader:
697                  */
698                 ptrace = leader->ptrace;
699                 parent = leader->parent;
700
701                 ptrace_unlink(current);
702                 ptrace_unlink(leader);
703                 remove_parent(current);
704                 remove_parent(leader);
705
706                 switch_exec_pids(leader, current);
707
708                 current->parent = current->real_parent = leader->real_parent;
709                 leader->parent = leader->real_parent = child_reaper;
710                 current->group_leader = current;
711                 leader->group_leader = leader;
712
713                 add_parent(current, current->parent);
714                 add_parent(leader, leader->parent);
715                 if (ptrace) {
716                         current->ptrace = ptrace;
717                         __ptrace_link(current, parent);
718                 }
719
720                 list_del(&current->tasks);
721                 list_add_tail(&current->tasks, &init_task.tasks);
722                 current->exit_signal = SIGCHLD;
723                 state = leader->state;
724
725                 write_unlock_irq(&tasklist_lock);
726                 spin_unlock(&leader->proc_lock);
727                 spin_unlock(&current->proc_lock);
728                 proc_pid_flush(proc_dentry1);
729                 proc_pid_flush(proc_dentry2);
730
731                 if (state != TASK_ZOMBIE)
732                         BUG();
733                 release_task(leader);
734         }
735
736 no_thread_group:
737
738         write_lock_irq(&tasklist_lock);
739         spin_lock(&oldsighand->siglock);
740         spin_lock(&newsighand->siglock);
741
742         if (current == oldsig->curr_target)
743                 oldsig->curr_target = next_thread(current);
744         if (newsig)
745                 current->signal = newsig;
746         current->sighand = newsighand;
747         init_sigpending(&current->pending);
748         recalc_sigpending();
749
750         spin_unlock(&newsighand->siglock);
751         spin_unlock(&oldsighand->siglock);
752         write_unlock_irq(&tasklist_lock);
753
754         if (newsig && atomic_dec_and_test(&oldsig->count))
755                 kmem_cache_free(signal_cachep, oldsig);
756
757         if (atomic_dec_and_test(&oldsighand->count))
758                 kmem_cache_free(sighand_cachep, oldsighand);
759
760         if (!thread_group_empty(current))
761                 BUG();
762         if (current->tgid != current->pid)
763                 BUG();
764         return 0;
765 }
766         
767 /*
768  * These functions flushes out all traces of the currently running executable
769  * so that a new one can be started
770  */
771
772 static inline void flush_old_files(struct files_struct * files)
773 {
774         long j = -1;
775
776         spin_lock(&files->file_lock);
777         for (;;) {
778                 unsigned long set, i;
779
780                 j++;
781                 i = j * __NFDBITS;
782                 if (i >= files->max_fds || i >= files->max_fdset)
783                         break;
784                 set = files->close_on_exec->fds_bits[j];
785                 if (!set)
786                         continue;
787                 files->close_on_exec->fds_bits[j] = 0;
788                 spin_unlock(&files->file_lock);
789                 for ( ; set ; i++,set >>= 1) {
790                         if (set & 1) {
791                                 sys_close(i);
792                         }
793                 }
794                 spin_lock(&files->file_lock);
795
796         }
797         spin_unlock(&files->file_lock);
798 }
799
800 int flush_old_exec(struct linux_binprm * bprm)
801 {
802         char * name;
803         int i, ch, retval;
804         struct files_struct *files;
805
806         /*
807          * Make sure we have a private signal table and that
808          * we are unassociated from the previous thread group.
809          */
810         retval = de_thread(current);
811         if (retval)
812                 goto out;
813
814         /*
815          * Make sure we have private file handles. Ask the
816          * fork helper to do the work for us and the exit
817          * helper to do the cleanup of the old one.
818          */
819         files = current->files;         /* refcounted so safe to hold */
820         retval = unshare_files();
821         if (retval)
822                 goto out;
823         /*
824          * Release all of the old mmap stuff
825          */
826         retval = exec_mmap(bprm->mm);
827         if (retval)
828                 goto mmap_failed;
829
830         bprm->mm = NULL;                /* We're using it now */
831
832         /* This is the point of no return */
833         steal_locks(files);
834         put_files_struct(files);
835
836         current->sas_ss_sp = current->sas_ss_size = 0;
837
838         if (current->euid == current->uid && current->egid == current->gid)
839                 current->mm->dumpable = 1;
840         name = bprm->filename;
841         for (i=0; (ch = *(name++)) != '\0';) {
842                 if (ch == '/')
843                         i = 0;
844                 else
845                         if (i < 15)
846                                 current->comm[i++] = ch;
847         }
848         current->comm[i] = '\0';
849
850         current->flags &= ~PF_RELOCEXEC;
851         flush_thread();
852
853         if (bprm->e_uid != current->euid || bprm->e_gid != current->egid || 
854             permission(bprm->file->f_dentry->d_inode,MAY_READ, NULL) ||
855             (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP))
856                 current->mm->dumpable = 0;
857
858         /* An exec changes our domain. We are no longer part of the thread
859            group */
860
861         current->self_exec_id++;
862                         
863         flush_signal_handlers(current, 0);
864         flush_old_files(current->files);
865
866         return 0;
867
868 mmap_failed:
869         put_files_struct(current->files);
870         current->files = files;
871 out:
872         return retval;
873 }
874
875 EXPORT_SYMBOL(flush_old_exec);
876
877 /* 
878  * Fill the binprm structure from the inode. 
879  * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
880  */
881 int prepare_binprm(struct linux_binprm *bprm)
882 {
883         int mode;
884         struct inode * inode = bprm->file->f_dentry->d_inode;
885         int retval;
886
887         mode = inode->i_mode;
888         /*
889          * Check execute perms again - if the caller has CAP_DAC_OVERRIDE,
890          * vfs_permission lets a non-executable through
891          */
892         if (!(mode & 0111))     /* with at least _one_ execute bit set */
893                 return -EACCES;
894         if (bprm->file->f_op == NULL)
895                 return -EACCES;
896
897         bprm->e_uid = current->euid;
898         bprm->e_gid = current->egid;
899
900         if(!(bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)) {
901                 /* Set-uid? */
902                 if (mode & S_ISUID) {
903                         current->personality &= ~PER_CLEAR_ON_SETID;
904                         bprm->e_uid = inode->i_uid;
905                 }
906
907                 /* Set-gid? */
908                 /*
909                  * If setgid is set but no group execute bit then this
910                  * is a candidate for mandatory locking, not a setgid
911                  * executable.
912                  */
913                 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
914                         current->personality &= ~PER_CLEAR_ON_SETID;
915                         bprm->e_gid = inode->i_gid;
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                                 ckrm_cb_exec(bprm->filename);
1051                                 return retval;
1052                         }
1053                         read_lock(&binfmt_lock);
1054                         put_binfmt(fmt);
1055                         if (retval != -ENOEXEC || bprm->mm == NULL)
1056                                 break;
1057                         if (!bprm->file) {
1058                                 read_unlock(&binfmt_lock);
1059                                 return retval;
1060                         }
1061                 }
1062                 read_unlock(&binfmt_lock);
1063                 if (retval != -ENOEXEC || bprm->mm == NULL) {
1064                         break;
1065 #ifdef CONFIG_KMOD
1066                 }else{
1067 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
1068                         if (printable(bprm->buf[0]) &&
1069                             printable(bprm->buf[1]) &&
1070                             printable(bprm->buf[2]) &&
1071                             printable(bprm->buf[3]))
1072                                 break; /* -ENOEXEC */
1073                         request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
1074 #endif
1075                 }
1076         }
1077         return retval;
1078 }
1079
1080 EXPORT_SYMBOL(search_binary_handler);
1081
1082 /*
1083  * sys_execve() executes a new program.
1084  */
1085 int do_execve(char * filename,
1086         char __user *__user *argv,
1087         char __user *__user *envp,
1088         struct pt_regs * regs)
1089 {
1090         struct linux_binprm bprm;
1091         struct file *file;
1092         int retval;
1093         int i;
1094
1095         file = open_exec(filename);
1096
1097         retval = PTR_ERR(file);
1098         if (IS_ERR(file))
1099                 return retval;
1100
1101         sched_balance_exec();
1102
1103         bprm.p = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1104         memset(bprm.page, 0, MAX_ARG_PAGES*sizeof(bprm.page[0]));
1105
1106         bprm.file = file;
1107         bprm.filename = filename;
1108         bprm.interp = filename;
1109         bprm.interp_flags = 0;
1110         bprm.interp_data = 0;
1111         bprm.sh_bang = 0;
1112         bprm.loader = 0;
1113         bprm.exec = 0;
1114         bprm.security = NULL;
1115         bprm.mm = mm_alloc();
1116         retval = -ENOMEM;
1117         if (!bprm.mm)
1118                 goto out_file;
1119
1120         retval = init_new_context(current, bprm.mm);
1121         if (retval < 0)
1122                 goto out_mm;
1123
1124         bprm.argc = count(argv, bprm.p / sizeof(void *));
1125         if ((retval = bprm.argc) < 0)
1126                 goto out_mm;
1127
1128         bprm.envc = count(envp, bprm.p / sizeof(void *));
1129         if ((retval = bprm.envc) < 0)
1130                 goto out_mm;
1131
1132         retval = security_bprm_alloc(&bprm);
1133         if (retval)
1134                 goto out;
1135
1136         retval = prepare_binprm(&bprm);
1137         if (retval < 0)
1138                 goto out;
1139
1140         retval = copy_strings_kernel(1, &bprm.filename, &bprm);
1141         if (retval < 0)
1142                 goto out;
1143
1144         bprm.exec = bprm.p;
1145         retval = copy_strings(bprm.envc, envp, &bprm);
1146         if (retval < 0)
1147                 goto out;
1148
1149         retval = copy_strings(bprm.argc, argv, &bprm);
1150         if (retval < 0)
1151                 goto out;
1152
1153         retval = search_binary_handler(&bprm,regs);
1154         if (retval >= 0) {
1155                 free_arg_pages(&bprm);
1156
1157                 /* execve success */
1158                 security_bprm_free(&bprm);
1159                 return retval;
1160         }
1161
1162 out:
1163         /* Something went wrong, return the inode and free the argument pages*/
1164         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
1165                 struct page * page = bprm.page[i];
1166                 if (page)
1167                         __free_page(page);
1168         }
1169
1170         if (bprm.security)
1171                 security_bprm_free(&bprm);
1172
1173 out_mm:
1174         if (bprm.mm)
1175                 mmdrop(bprm.mm);
1176
1177 out_file:
1178         if (bprm.file) {
1179                 allow_write_access(bprm.file);
1180                 fput(bprm.file);
1181         }
1182         return retval;
1183 }
1184
1185 EXPORT_SYMBOL(do_execve);
1186
1187 int set_binfmt(struct linux_binfmt *new)
1188 {
1189         struct linux_binfmt *old = current->binfmt;
1190
1191         if (new) {
1192                 if (!try_module_get(new->module))
1193                         return -1;
1194         }
1195         current->binfmt = new;
1196         if (old)
1197                 module_put(old->module);
1198         return 0;
1199 }
1200
1201 EXPORT_SYMBOL(set_binfmt);
1202
1203 #define CORENAME_MAX_SIZE 64
1204
1205 /* format_corename will inspect the pattern parameter, and output a
1206  * name into corename, which must have space for at least
1207  * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
1208  */
1209 void format_corename(char *corename, const char *pattern, long signr)
1210 {
1211         const char *pat_ptr = pattern;
1212         char *out_ptr = corename;
1213         char *const out_end = corename + CORENAME_MAX_SIZE;
1214         int rc;
1215         int pid_in_pattern = 0;
1216
1217         /* Repeat as long as we have more pattern to process and more output
1218            space */
1219         while (*pat_ptr) {
1220                 if (*pat_ptr != '%') {
1221                         if (out_ptr == out_end)
1222                                 goto out;
1223                         *out_ptr++ = *pat_ptr++;
1224                 } else {
1225                         switch (*++pat_ptr) {
1226                         case 0:
1227                                 goto out;
1228                         /* Double percent, output one percent */
1229                         case '%':
1230                                 if (out_ptr == out_end)
1231                                         goto out;
1232                                 *out_ptr++ = '%';
1233                                 break;
1234                         /* pid */
1235                         case 'p':
1236                                 pid_in_pattern = 1;
1237                                 rc = snprintf(out_ptr, out_end - out_ptr,
1238                                               "%d", current->tgid);
1239                                 if (rc > out_end - out_ptr)
1240                                         goto out;
1241                                 out_ptr += rc;
1242                                 break;
1243                         /* uid */
1244                         case 'u':
1245                                 rc = snprintf(out_ptr, out_end - out_ptr,
1246                                               "%d", current->uid);
1247                                 if (rc > out_end - out_ptr)
1248                                         goto out;
1249                                 out_ptr += rc;
1250                                 break;
1251                         /* gid */
1252                         case 'g':
1253                                 rc = snprintf(out_ptr, out_end - out_ptr,
1254                                               "%d", current->gid);
1255                                 if (rc > out_end - out_ptr)
1256                                         goto out;
1257                                 out_ptr += rc;
1258                                 break;
1259                         /* signal that caused the coredump */
1260                         case 's':
1261                                 rc = snprintf(out_ptr, out_end - out_ptr,
1262                                               "%ld", signr);
1263                                 if (rc > out_end - out_ptr)
1264                                         goto out;
1265                                 out_ptr += rc;
1266                                 break;
1267                         /* UNIX time of coredump */
1268                         case 't': {
1269                                 struct timeval tv;
1270                                 do_gettimeofday(&tv);
1271                                 rc = snprintf(out_ptr, out_end - out_ptr,
1272                                               "%lu", tv.tv_sec);
1273                                 if (rc > out_end - out_ptr)
1274                                         goto out;
1275                                 out_ptr += rc;
1276                                 break;
1277                         }
1278                         /* hostname */
1279                         case 'h':
1280                                 down_read(&uts_sem);
1281                                 rc = snprintf(out_ptr, out_end - out_ptr,
1282                                               "%s", system_utsname.nodename);
1283                                 up_read(&uts_sem);
1284                                 if (rc > out_end - out_ptr)
1285                                         goto out;
1286                                 out_ptr += rc;
1287                                 break;
1288                         /* executable */
1289                         case 'e':
1290                                 rc = snprintf(out_ptr, out_end - out_ptr,
1291                                               "%s", current->comm);
1292                                 if (rc > out_end - out_ptr)
1293                                         goto out;
1294                                 out_ptr += rc;
1295                                 break;
1296                         default:
1297                                 break;
1298                         }
1299                         ++pat_ptr;
1300                 }
1301         }
1302         /* Backward compatibility with core_uses_pid:
1303          *
1304          * If core_pattern does not include a %p (as is the default)
1305          * and core_uses_pid is set, then .%pid will be appended to
1306          * the filename */
1307         if (!pid_in_pattern
1308             && (core_uses_pid || atomic_read(&current->mm->mm_users) != 1)) {
1309                 rc = snprintf(out_ptr, out_end - out_ptr,
1310                               ".%d", current->tgid);
1311                 if (rc > out_end - out_ptr)
1312                         goto out;
1313                 out_ptr += rc;
1314         }
1315       out:
1316         *out_ptr = 0;
1317 }
1318
1319 static void zap_threads (struct mm_struct *mm)
1320 {
1321         struct task_struct *g, *p;
1322         struct task_struct *tsk = current;
1323         struct completion *vfork_done = tsk->vfork_done;
1324
1325         /*
1326          * Make sure nobody is waiting for us to release the VM,
1327          * otherwise we can deadlock when we wait on each other
1328          */
1329         if (vfork_done) {
1330                 tsk->vfork_done = NULL;
1331                 complete(vfork_done);
1332         }
1333
1334         read_lock(&tasklist_lock);
1335         do_each_thread(g,p)
1336                 if (mm == p->mm && p != tsk) {
1337                         force_sig_specific(SIGKILL, p);
1338                         mm->core_waiters++;
1339                 }
1340         while_each_thread(g,p);
1341
1342         read_unlock(&tasklist_lock);
1343 }
1344
1345 static void coredump_wait(struct mm_struct *mm)
1346 {
1347         DECLARE_COMPLETION(startup_done);
1348
1349         mm->core_waiters++; /* let other threads block */
1350         mm->core_startup_done = &startup_done;
1351
1352         /* give other threads a chance to run: */
1353         yield();
1354
1355         zap_threads(mm);
1356         if (--mm->core_waiters) {
1357                 up_write(&mm->mmap_sem);
1358                 wait_for_completion(&startup_done);
1359         } else
1360                 up_write(&mm->mmap_sem);
1361         BUG_ON(mm->core_waiters);
1362 }
1363
1364 int do_coredump(long signr, int exit_code, struct pt_regs * regs)
1365 {
1366         char corename[CORENAME_MAX_SIZE + 1];
1367         struct mm_struct *mm = current->mm;
1368         struct linux_binfmt * binfmt;
1369         struct inode * inode;
1370         struct file * file;
1371         int retval = 0;
1372
1373         lock_kernel();
1374         binfmt = current->binfmt;
1375         if (!binfmt || !binfmt->core_dump)
1376                 goto fail;
1377         down_write(&mm->mmap_sem);
1378         if (!mm->dumpable) {
1379                 up_write(&mm->mmap_sem);
1380                 goto fail;
1381         }
1382         mm->dumpable = 0;
1383         init_completion(&mm->core_done);
1384         current->signal->group_exit = 1;
1385         current->signal->group_exit_code = exit_code;
1386         coredump_wait(mm);
1387
1388         if (current->rlim[RLIMIT_CORE].rlim_cur < binfmt->min_coredump)
1389                 goto fail_unlock;
1390
1391         format_corename(corename, core_pattern, signr);
1392         file = filp_open(corename, O_CREAT | 2 | O_NOFOLLOW | O_LARGEFILE, 0600);
1393         if (IS_ERR(file))
1394                 goto fail_unlock;
1395         inode = file->f_dentry->d_inode;
1396         if (inode->i_nlink > 1)
1397                 goto close_fail;        /* multiple links - don't dump */
1398         if (d_unhashed(file->f_dentry))
1399                 goto close_fail;
1400
1401         if (!S_ISREG(inode->i_mode))
1402                 goto close_fail;
1403         if (!file->f_op)
1404                 goto close_fail;
1405         if (!file->f_op->write)
1406                 goto close_fail;
1407         if (do_truncate(file->f_dentry, 0) != 0)
1408                 goto close_fail;
1409
1410         retval = binfmt->core_dump(signr, regs, file);
1411
1412         current->signal->group_exit_code |= 0x80;
1413 close_fail:
1414         filp_close(file, NULL);
1415 fail_unlock:
1416         complete_all(&mm->core_done);
1417 fail:
1418         unlock_kernel();
1419         return retval;
1420 }