vserver 1.9.3
[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/vs_memory.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         stack_base = STACK_TOP - MAX_ARG_PAGES * PAGE_SIZE;
395         mm->arg_start = bprm->p + stack_base;
396         arg_size = STACK_TOP - (PAGE_MASK & (unsigned long) mm->arg_start);
397 #endif
398
399         bprm->p += stack_base;
400         if (bprm->loader)
401                 bprm->loader += stack_base;
402         bprm->exec += stack_base;
403
404         mpnt = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
405         if (!mpnt)
406                 return -ENOMEM;
407
408         if (security_vm_enough_memory(arg_size >> PAGE_SHIFT) ||
409                 !vx_vmpages_avail(mm, arg_size >> PAGE_SHIFT)) {
410                 kmem_cache_free(vm_area_cachep, mpnt);
411                 return -ENOMEM;
412         }
413
414         memset(mpnt, 0, sizeof(*mpnt));
415
416         down_write(&mm->mmap_sem);
417         {
418                 mpnt->vm_mm = mm;
419 #ifdef CONFIG_STACK_GROWSUP
420                 mpnt->vm_start = stack_base;
421                 mpnt->vm_end = PAGE_MASK &
422                         (PAGE_SIZE - 1 + (unsigned long) bprm->p);
423 #else
424                 mpnt->vm_start = PAGE_MASK & (unsigned long) bprm->p;
425                 mpnt->vm_end = STACK_TOP;
426 #endif
427                 /* Adjust stack execute permissions; explicitly enable
428                  * for EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X
429                  * and leave alone (arch default) otherwise. */
430                 if (unlikely(executable_stack == EXSTACK_ENABLE_X))
431                         mpnt->vm_flags = VM_STACK_FLAGS |  VM_EXEC;
432                 else if (executable_stack == EXSTACK_DISABLE_X)
433                         mpnt->vm_flags = VM_STACK_FLAGS & ~VM_EXEC;
434                 else
435                         mpnt->vm_flags = VM_STACK_FLAGS;
436                 mpnt->vm_flags |= mm->def_flags;
437                 mpnt->vm_page_prot = protection_map[mpnt->vm_flags & 0x7];
438                 insert_vm_struct(mm, mpnt);
439                 // mm->stack_vm = mm->total_vm = vma_pages(mpnt);
440                 vx_vmpages_sub(mm, mm->total_vm - vma_pages(mpnt));
441                 mm->stack_vm = mm->total_vm;
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         arch_pick_mmap_layout(mm);
555         if (old_mm) {
556                 if (active_mm != old_mm) BUG();
557                 mmput(old_mm);
558                 return 0;
559         }
560         mmdrop(active_mm);
561         return 0;
562 }
563
564 /*
565  * This function makes sure the current process has its own signal table,
566  * so that flush_signal_handlers can later reset the handlers without
567  * disturbing other processes.  (Other processes might share the signal
568  * table via the CLONE_SIGHAND option to clone().)
569  */
570 static inline int de_thread(struct task_struct *tsk)
571 {
572         struct signal_struct *newsig, *oldsig = tsk->signal;
573         struct sighand_struct *newsighand, *oldsighand = tsk->sighand;
574         spinlock_t *lock = &oldsighand->siglock;
575         int count;
576
577         /*
578          * If we don't share sighandlers, then we aren't sharing anything
579          * and we can just re-use it all.
580          */
581         if (atomic_read(&oldsighand->count) <= 1)
582                 return 0;
583
584         newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
585         if (!newsighand)
586                 return -ENOMEM;
587
588         spin_lock_init(&newsighand->siglock);
589         atomic_set(&newsighand->count, 1);
590         memcpy(newsighand->action, oldsighand->action, sizeof(newsighand->action));
591
592         /*
593          * See if we need to allocate a new signal structure
594          */
595         newsig = NULL;
596         if (atomic_read(&oldsig->count) > 1) {
597                 newsig = kmem_cache_alloc(signal_cachep, GFP_KERNEL);
598                 if (!newsig) {
599                         kmem_cache_free(sighand_cachep, newsighand);
600                         return -ENOMEM;
601                 }
602                 atomic_set(&newsig->count, 1);
603                 newsig->group_exit = 0;
604                 newsig->group_exit_code = 0;
605                 newsig->group_exit_task = NULL;
606                 newsig->group_stop_count = 0;
607                 newsig->curr_target = NULL;
608                 init_sigpending(&newsig->shared_pending);
609                 INIT_LIST_HEAD(&newsig->posix_timers);
610
611                 newsig->tty = oldsig->tty;
612                 newsig->pgrp = oldsig->pgrp;
613                 newsig->session = oldsig->session;
614                 newsig->leader = oldsig->leader;
615                 newsig->tty_old_pgrp = oldsig->tty_old_pgrp;
616         }
617
618         if (thread_group_empty(current))
619                 goto no_thread_group;
620
621         /*
622          * Kill all other threads in the thread group.
623          * We must hold tasklist_lock to call zap_other_threads.
624          */
625         read_lock(&tasklist_lock);
626         spin_lock_irq(lock);
627         if (oldsig->group_exit) {
628                 /*
629                  * Another group action in progress, just
630                  * return so that the signal is processed.
631                  */
632                 spin_unlock_irq(lock);
633                 read_unlock(&tasklist_lock);
634                 kmem_cache_free(sighand_cachep, newsighand);
635                 if (newsig)
636                         kmem_cache_free(signal_cachep, newsig);
637                 return -EAGAIN;
638         }
639         oldsig->group_exit = 1;
640         zap_other_threads(current);
641         read_unlock(&tasklist_lock);
642
643         /*
644          * Account for the thread group leader hanging around:
645          */
646         count = 2;
647         if (current->pid == current->tgid)
648                 count = 1;
649         while (atomic_read(&oldsig->count) > count) {
650                 oldsig->group_exit_task = current;
651                 oldsig->notify_count = count;
652                 __set_current_state(TASK_UNINTERRUPTIBLE);
653                 spin_unlock_irq(lock);
654                 schedule();
655                 spin_lock_irq(lock);
656         }
657         spin_unlock_irq(lock);
658
659         /*
660          * At this point all other threads have exited, all we have to
661          * do is to wait for the thread group leader to become inactive,
662          * and to assume its PID:
663          */
664         if (current->pid != current->tgid) {
665                 struct task_struct *leader = current->group_leader, *parent;
666                 struct dentry *proc_dentry1, *proc_dentry2;
667                 unsigned long state, ptrace;
668
669                 /*
670                  * Wait for the thread group leader to be a zombie.
671                  * It should already be zombie at this point, most
672                  * of the time.
673                  */
674                 while (leader->state != TASK_ZOMBIE)
675                         yield();
676
677                 spin_lock(&leader->proc_lock);
678                 spin_lock(&current->proc_lock);
679                 proc_dentry1 = proc_pid_unhash(current);
680                 proc_dentry2 = proc_pid_unhash(leader);
681                 write_lock_irq(&tasklist_lock);
682
683                 if (leader->tgid != current->tgid)
684                         BUG();
685                 if (current->pid == current->tgid)
686                         BUG();
687                 /*
688                  * An exec() starts a new thread group with the
689                  * TGID of the previous thread group. Rehash the
690                  * two threads with a switched PID, and release
691                  * the former thread group leader:
692                  */
693                 ptrace = leader->ptrace;
694                 parent = leader->parent;
695
696                 ptrace_unlink(current);
697                 ptrace_unlink(leader);
698                 remove_parent(current);
699                 remove_parent(leader);
700
701                 switch_exec_pids(leader, current);
702
703                 current->parent = current->real_parent = leader->real_parent;
704                 leader->parent = leader->real_parent = child_reaper;
705                 current->group_leader = current;
706                 leader->group_leader = leader;
707
708                 add_parent(current, current->parent);
709                 add_parent(leader, leader->parent);
710                 if (ptrace) {
711                         current->ptrace = ptrace;
712                         __ptrace_link(current, parent);
713                 }
714
715                 list_del(&current->tasks);
716                 list_add_tail(&current->tasks, &init_task.tasks);
717                 current->exit_signal = SIGCHLD;
718                 state = leader->state;
719
720                 write_unlock_irq(&tasklist_lock);
721                 spin_unlock(&leader->proc_lock);
722                 spin_unlock(&current->proc_lock);
723                 proc_pid_flush(proc_dentry1);
724                 proc_pid_flush(proc_dentry2);
725
726                 if (state != TASK_ZOMBIE)
727                         BUG();
728                 release_task(leader);
729         }
730
731 no_thread_group:
732
733         write_lock_irq(&tasklist_lock);
734         spin_lock(&oldsighand->siglock);
735         spin_lock(&newsighand->siglock);
736
737         if (current == oldsig->curr_target)
738                 oldsig->curr_target = next_thread(current);
739         if (newsig)
740                 current->signal = newsig;
741         current->sighand = newsighand;
742         init_sigpending(&current->pending);
743         recalc_sigpending();
744
745         spin_unlock(&newsighand->siglock);
746         spin_unlock(&oldsighand->siglock);
747         write_unlock_irq(&tasklist_lock);
748
749         if (newsig && atomic_dec_and_test(&oldsig->count)) {
750                 exit_itimers(oldsig);
751                 kmem_cache_free(signal_cachep, oldsig);
752         }
753
754         if (atomic_dec_and_test(&oldsighand->count))
755                 kmem_cache_free(sighand_cachep, oldsighand);
756
757         if (!thread_group_empty(current))
758                 BUG();
759         if (current->tgid != current->pid)
760                 BUG();
761         return 0;
762 }
763         
764 /*
765  * These functions flushes out all traces of the currently running executable
766  * so that a new one can be started
767  */
768
769 static inline void flush_old_files(struct files_struct * files)
770 {
771         long j = -1;
772
773         spin_lock(&files->file_lock);
774         for (;;) {
775                 unsigned long set, i;
776
777                 j++;
778                 i = j * __NFDBITS;
779                 if (i >= files->max_fds || i >= files->max_fdset)
780                         break;
781                 set = files->close_on_exec->fds_bits[j];
782                 if (!set)
783                         continue;
784                 files->close_on_exec->fds_bits[j] = 0;
785                 spin_unlock(&files->file_lock);
786                 for ( ; set ; i++,set >>= 1) {
787                         if (set & 1) {
788                                 sys_close(i);
789                         }
790                 }
791                 spin_lock(&files->file_lock);
792
793         }
794         spin_unlock(&files->file_lock);
795 }
796
797 void get_task_comm(char *buf, struct task_struct *tsk)
798 {
799         /* buf must be at least sizeof(tsk->comm) in size */
800         task_lock(tsk);
801         memcpy(buf, tsk->comm, sizeof(tsk->comm));
802         task_unlock(tsk);
803 }
804
805 void set_task_comm(struct task_struct *tsk, char *buf)
806 {
807         task_lock(tsk);
808         strlcpy(tsk->comm, buf, sizeof(tsk->comm));
809         task_unlock(tsk);
810 }
811
812 int flush_old_exec(struct linux_binprm * bprm)
813 {
814         char * name;
815         int i, ch, retval;
816         struct files_struct *files;
817         char tcomm[sizeof(current->comm)];
818
819         /*
820          * Make sure we have a private signal table and that
821          * we are unassociated from the previous thread group.
822          */
823         retval = de_thread(current);
824         if (retval)
825                 goto out;
826
827         /*
828          * Make sure we have private file handles. Ask the
829          * fork helper to do the work for us and the exit
830          * helper to do the cleanup of the old one.
831          */
832         files = current->files;         /* refcounted so safe to hold */
833         retval = unshare_files();
834         if (retval)
835                 goto out;
836         /*
837          * Release all of the old mmap stuff
838          */
839         retval = exec_mmap(bprm->mm);
840         if (retval)
841                 goto mmap_failed;
842
843         bprm->mm = NULL;                /* We're using it now */
844
845         /* This is the point of no return */
846         steal_locks(files);
847         put_files_struct(files);
848
849         current->sas_ss_sp = current->sas_ss_size = 0;
850
851         if (current->euid == current->uid && current->egid == current->gid)
852                 current->mm->dumpable = 1;
853         name = bprm->filename;
854         for (i=0; (ch = *(name++)) != '\0';) {
855                 if (ch == '/')
856                         i = 0;
857                 else
858                         if (i < (sizeof(tcomm) - 1))
859                                 tcomm[i++] = ch;
860         }
861         tcomm[i] = '\0';
862         set_task_comm(current, tcomm);
863
864         flush_thread();
865
866         if (bprm->e_uid != current->euid || bprm->e_gid != current->egid || 
867             permission(bprm->file->f_dentry->d_inode,MAY_READ, NULL) ||
868             (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP))
869                 current->mm->dumpable = 0;
870
871         /* An exec changes our domain. We are no longer part of the thread
872            group */
873
874         current->self_exec_id++;
875                         
876         flush_signal_handlers(current, 0);
877         flush_old_files(current->files);
878
879         return 0;
880
881 mmap_failed:
882         put_files_struct(current->files);
883         current->files = files;
884 out:
885         return retval;
886 }
887
888 EXPORT_SYMBOL(flush_old_exec);
889
890 /* 
891  * Fill the binprm structure from the inode. 
892  * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
893  */
894 int prepare_binprm(struct linux_binprm *bprm)
895 {
896         int mode;
897         struct inode * inode = bprm->file->f_dentry->d_inode;
898         int retval;
899
900         mode = inode->i_mode;
901         /*
902          * Check execute perms again - if the caller has CAP_DAC_OVERRIDE,
903          * vfs_permission lets a non-executable through
904          */
905         if (!(mode & 0111))     /* with at least _one_ execute bit set */
906                 return -EACCES;
907         if (bprm->file->f_op == NULL)
908                 return -EACCES;
909
910         bprm->e_uid = current->euid;
911         bprm->e_gid = current->egid;
912
913         if(!(bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)) {
914                 /* Set-uid? */
915                 if (mode & S_ISUID) {
916                         current->personality &= ~PER_CLEAR_ON_SETID;
917                         bprm->e_uid = inode->i_uid;
918                 }
919
920                 /* Set-gid? */
921                 /*
922                  * If setgid is set but no group execute bit then this
923                  * is a candidate for mandatory locking, not a setgid
924                  * executable.
925                  */
926                 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
927                         current->personality &= ~PER_CLEAR_ON_SETID;
928                         bprm->e_gid = inode->i_gid;
929                 }
930         }
931
932         /* fill in binprm security blob */
933         retval = security_bprm_set(bprm);
934         if (retval)
935                 return retval;
936
937         memset(bprm->buf,0,BINPRM_BUF_SIZE);
938         return kernel_read(bprm->file,0,bprm->buf,BINPRM_BUF_SIZE);
939 }
940
941 EXPORT_SYMBOL(prepare_binprm);
942
943 static inline int unsafe_exec(struct task_struct *p)
944 {
945         int unsafe = 0;
946         if (p->ptrace & PT_PTRACED) {
947                 if (p->ptrace & PT_PTRACE_CAP)
948                         unsafe |= LSM_UNSAFE_PTRACE_CAP;
949                 else
950                         unsafe |= LSM_UNSAFE_PTRACE;
951         }
952         if (atomic_read(&p->fs->count) > 1 ||
953             atomic_read(&p->files->count) > 1 ||
954             atomic_read(&p->sighand->count) > 1)
955                 unsafe |= LSM_UNSAFE_SHARE;
956
957         return unsafe;
958 }
959
960 void compute_creds(struct linux_binprm *bprm)
961 {
962         int unsafe;
963         task_lock(current);
964         unsafe = unsafe_exec(current);
965         security_bprm_apply_creds(bprm, unsafe);
966         task_unlock(current);
967 }
968
969 EXPORT_SYMBOL(compute_creds);
970
971 void remove_arg_zero(struct linux_binprm *bprm)
972 {
973         if (bprm->argc) {
974                 unsigned long offset;
975                 char * kaddr;
976                 struct page *page;
977
978                 offset = bprm->p % PAGE_SIZE;
979                 goto inside;
980
981                 while (bprm->p++, *(kaddr+offset++)) {
982                         if (offset != PAGE_SIZE)
983                                 continue;
984                         offset = 0;
985                         kunmap_atomic(kaddr, KM_USER0);
986 inside:
987                         page = bprm->page[bprm->p/PAGE_SIZE];
988                         kaddr = kmap_atomic(page, KM_USER0);
989                 }
990                 kunmap_atomic(kaddr, KM_USER0);
991                 bprm->argc--;
992         }
993 }
994
995 EXPORT_SYMBOL(remove_arg_zero);
996
997 /*
998  * cycle the list of binary formats handler, until one recognizes the image
999  */
1000 int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs)
1001 {
1002         int try,retval=0;
1003         struct linux_binfmt *fmt;
1004 #ifdef __alpha__
1005         /* handle /sbin/loader.. */
1006         {
1007             struct exec * eh = (struct exec *) bprm->buf;
1008
1009             if (!bprm->loader && eh->fh.f_magic == 0x183 &&
1010                 (eh->fh.f_flags & 0x3000) == 0x3000)
1011             {
1012                 struct file * file;
1013                 unsigned long loader;
1014
1015                 allow_write_access(bprm->file);
1016                 fput(bprm->file);
1017                 bprm->file = NULL;
1018
1019                 loader = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1020
1021                 file = open_exec("/sbin/loader");
1022                 retval = PTR_ERR(file);
1023                 if (IS_ERR(file))
1024                         return retval;
1025
1026                 /* Remember if the application is TASO.  */
1027                 bprm->sh_bang = eh->ah.entry < 0x100000000UL;
1028
1029                 bprm->file = file;
1030                 bprm->loader = loader;
1031                 retval = prepare_binprm(bprm);
1032                 if (retval<0)
1033                         return retval;
1034                 /* should call search_binary_handler recursively here,
1035                    but it does not matter */
1036             }
1037         }
1038 #endif
1039         retval = security_bprm_check(bprm);
1040         if (retval)
1041                 return retval;
1042
1043         /* kernel module loader fixup */
1044         /* so we don't try to load run modprobe in kernel space. */
1045         set_fs(USER_DS);
1046         for (try=0; try<2; try++) {
1047                 read_lock(&binfmt_lock);
1048                 for (fmt = formats ; fmt ; fmt = fmt->next) {
1049                         int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
1050                         if (!fn)
1051                                 continue;
1052                         if (!try_module_get(fmt->module))
1053                                 continue;
1054                         read_unlock(&binfmt_lock);
1055                         retval = fn(bprm, regs);
1056                         if (retval >= 0) {
1057                                 put_binfmt(fmt);
1058                                 allow_write_access(bprm->file);
1059                                 if (bprm->file)
1060                                         fput(bprm->file);
1061                                 bprm->file = NULL;
1062                                 current->did_exec = 1;
1063                                 return retval;
1064                         }
1065                         read_lock(&binfmt_lock);
1066                         put_binfmt(fmt);
1067                         if (retval != -ENOEXEC || bprm->mm == NULL)
1068                                 break;
1069                         if (!bprm->file) {
1070                                 read_unlock(&binfmt_lock);
1071                                 return retval;
1072                         }
1073                 }
1074                 read_unlock(&binfmt_lock);
1075                 if (retval != -ENOEXEC || bprm->mm == NULL) {
1076                         break;
1077 #ifdef CONFIG_KMOD
1078                 }else{
1079 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
1080                         if (printable(bprm->buf[0]) &&
1081                             printable(bprm->buf[1]) &&
1082                             printable(bprm->buf[2]) &&
1083                             printable(bprm->buf[3]))
1084                                 break; /* -ENOEXEC */
1085                         request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
1086 #endif
1087                 }
1088         }
1089         return retval;
1090 }
1091
1092 EXPORT_SYMBOL(search_binary_handler);
1093
1094 /*
1095  * sys_execve() executes a new program.
1096  */
1097 int do_execve(char * filename,
1098         char __user *__user *argv,
1099         char __user *__user *envp,
1100         struct pt_regs * regs)
1101 {
1102         struct linux_binprm *bprm;
1103         struct file *file;
1104         int retval;
1105         int i;
1106
1107         file = open_exec(filename);
1108
1109         retval = PTR_ERR(file);
1110         if (IS_ERR(file))
1111                 return retval;
1112
1113         sched_exec();
1114
1115         retval = -ENOMEM;
1116         bprm = kmalloc(sizeof(*bprm), GFP_KERNEL);
1117         if (!bprm)
1118                 goto out_ret;
1119         memset(bprm, 0, sizeof(*bprm));
1120
1121         bprm->p = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1122
1123         bprm->file = file;
1124         bprm->filename = filename;
1125         bprm->interp = filename;
1126         bprm->mm = mm_alloc();
1127         if (!bprm->mm)
1128                 goto out_file;
1129
1130         retval = init_new_context(current, bprm->mm);
1131         if (retval < 0)
1132                 goto out_mm;
1133
1134         bprm->argc = count(argv, bprm->p / sizeof(void *));
1135         if ((retval = bprm->argc) < 0)
1136                 goto out_mm;
1137
1138         bprm->envc = count(envp, bprm->p / sizeof(void *));
1139         if ((retval = bprm->envc) < 0)
1140                 goto out_mm;
1141
1142         retval = security_bprm_alloc(bprm);
1143         if (retval)
1144                 goto out;
1145
1146         retval = prepare_binprm(bprm);
1147         if (retval < 0)
1148                 goto out;
1149
1150         retval = copy_strings_kernel(1, &bprm->filename, bprm);
1151         if (retval < 0)
1152                 goto out;
1153
1154         bprm->exec = bprm->p;
1155         retval = copy_strings(bprm->envc, envp, bprm);
1156         if (retval < 0)
1157                 goto out;
1158
1159         retval = copy_strings(bprm->argc, argv, bprm);
1160         if (retval < 0)
1161                 goto out;
1162
1163         retval = search_binary_handler(bprm,regs);
1164         if (retval >= 0) {
1165                 free_arg_pages(bprm);
1166
1167                 /* execve success */
1168                 security_bprm_free(bprm);
1169                 kfree(bprm);
1170                 return retval;
1171         }
1172
1173 out:
1174         /* Something went wrong, return the inode and free the argument pages*/
1175         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
1176                 struct page * page = bprm->page[i];
1177                 if (page)
1178                         __free_page(page);
1179         }
1180
1181         if (bprm->security)
1182                 security_bprm_free(bprm);
1183
1184 out_mm:
1185         if (bprm->mm)
1186                 mmdrop(bprm->mm);
1187
1188 out_file:
1189         if (bprm->file) {
1190                 allow_write_access(bprm->file);
1191                 fput(bprm->file);
1192         }
1193         kfree(bprm);
1194
1195 out_ret:
1196         return retval;
1197 }
1198
1199 EXPORT_SYMBOL(do_execve);
1200
1201 int set_binfmt(struct linux_binfmt *new)
1202 {
1203         struct linux_binfmt *old = current->binfmt;
1204
1205         if (new) {
1206                 if (!try_module_get(new->module))
1207                         return -1;
1208         }
1209         current->binfmt = new;
1210         if (old)
1211                 module_put(old->module);
1212         return 0;
1213 }
1214
1215 EXPORT_SYMBOL(set_binfmt);
1216
1217 #define CORENAME_MAX_SIZE 64
1218
1219 /* format_corename will inspect the pattern parameter, and output a
1220  * name into corename, which must have space for at least
1221  * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
1222  */
1223 static void format_corename(char *corename, const char *pattern, long signr)
1224 {
1225         const char *pat_ptr = pattern;
1226         char *out_ptr = corename;
1227         char *const out_end = corename + CORENAME_MAX_SIZE;
1228         int rc;
1229         int pid_in_pattern = 0;
1230
1231         /* Repeat as long as we have more pattern to process and more output
1232            space */
1233         while (*pat_ptr) {
1234                 if (*pat_ptr != '%') {
1235                         if (out_ptr == out_end)
1236                                 goto out;
1237                         *out_ptr++ = *pat_ptr++;
1238                 } else {
1239                         switch (*++pat_ptr) {
1240                         case 0:
1241                                 goto out;
1242                         /* Double percent, output one percent */
1243                         case '%':
1244                                 if (out_ptr == out_end)
1245                                         goto out;
1246                                 *out_ptr++ = '%';
1247                                 break;
1248                         /* pid */
1249                         case 'p':
1250                                 pid_in_pattern = 1;
1251                                 rc = snprintf(out_ptr, out_end - out_ptr,
1252                                               "%d", current->tgid);
1253                                 if (rc > out_end - out_ptr)
1254                                         goto out;
1255                                 out_ptr += rc;
1256                                 break;
1257                         /* uid */
1258                         case 'u':
1259                                 rc = snprintf(out_ptr, out_end - out_ptr,
1260                                               "%d", current->uid);
1261                                 if (rc > out_end - out_ptr)
1262                                         goto out;
1263                                 out_ptr += rc;
1264                                 break;
1265                         /* gid */
1266                         case 'g':
1267                                 rc = snprintf(out_ptr, out_end - out_ptr,
1268                                               "%d", current->gid);
1269                                 if (rc > out_end - out_ptr)
1270                                         goto out;
1271                                 out_ptr += rc;
1272                                 break;
1273                         /* signal that caused the coredump */
1274                         case 's':
1275                                 rc = snprintf(out_ptr, out_end - out_ptr,
1276                                               "%ld", signr);
1277                                 if (rc > out_end - out_ptr)
1278                                         goto out;
1279                                 out_ptr += rc;
1280                                 break;
1281                         /* UNIX time of coredump */
1282                         case 't': {
1283                                 struct timeval tv;
1284                                 do_gettimeofday(&tv);
1285                                 rc = snprintf(out_ptr, out_end - out_ptr,
1286                                               "%lu", tv.tv_sec);
1287                                 if (rc > out_end - out_ptr)
1288                                         goto out;
1289                                 out_ptr += rc;
1290                                 break;
1291                         }
1292                         /* hostname */
1293                         case 'h':
1294                                 down_read(&uts_sem);
1295                                 rc = snprintf(out_ptr, out_end - out_ptr,
1296                                               "%s", system_utsname.nodename);
1297                                 up_read(&uts_sem);
1298                                 if (rc > out_end - out_ptr)
1299                                         goto out;
1300                                 out_ptr += rc;
1301                                 break;
1302                         /* executable */
1303                         case 'e':
1304                                 rc = snprintf(out_ptr, out_end - out_ptr,
1305                                               "%s", current->comm);
1306                                 if (rc > out_end - out_ptr)
1307                                         goto out;
1308                                 out_ptr += rc;
1309                                 break;
1310                         default:
1311                                 break;
1312                         }
1313                         ++pat_ptr;
1314                 }
1315         }
1316         /* Backward compatibility with core_uses_pid:
1317          *
1318          * If core_pattern does not include a %p (as is the default)
1319          * and core_uses_pid is set, then .%pid will be appended to
1320          * the filename */
1321         if (!pid_in_pattern
1322             && (core_uses_pid || atomic_read(&current->mm->mm_users) != 1)) {
1323                 rc = snprintf(out_ptr, out_end - out_ptr,
1324                               ".%d", current->tgid);
1325                 if (rc > out_end - out_ptr)
1326                         goto out;
1327                 out_ptr += rc;
1328         }
1329       out:
1330         *out_ptr = 0;
1331 }
1332
1333 static void zap_threads (struct mm_struct *mm)
1334 {
1335         struct task_struct *g, *p;
1336         struct task_struct *tsk = current;
1337         struct completion *vfork_done = tsk->vfork_done;
1338
1339         /*
1340          * Make sure nobody is waiting for us to release the VM,
1341          * otherwise we can deadlock when we wait on each other
1342          */
1343         if (vfork_done) {
1344                 tsk->vfork_done = NULL;
1345                 complete(vfork_done);
1346         }
1347
1348         read_lock(&tasklist_lock);
1349         do_each_thread(g,p)
1350                 if (mm == p->mm && p != tsk) {
1351                         force_sig_specific(SIGKILL, p);
1352                         mm->core_waiters++;
1353                 }
1354         while_each_thread(g,p);
1355
1356         read_unlock(&tasklist_lock);
1357 }
1358
1359 static void coredump_wait(struct mm_struct *mm)
1360 {
1361         DECLARE_COMPLETION(startup_done);
1362
1363         mm->core_waiters++; /* let other threads block */
1364         mm->core_startup_done = &startup_done;
1365
1366         /* give other threads a chance to run: */
1367         yield();
1368
1369         zap_threads(mm);
1370         if (--mm->core_waiters) {
1371                 up_write(&mm->mmap_sem);
1372                 wait_for_completion(&startup_done);
1373         } else
1374                 up_write(&mm->mmap_sem);
1375         BUG_ON(mm->core_waiters);
1376 }
1377
1378 int do_coredump(long signr, int exit_code, struct pt_regs * regs)
1379 {
1380         char corename[CORENAME_MAX_SIZE + 1];
1381         struct mm_struct *mm = current->mm;
1382         struct linux_binfmt * binfmt;
1383         struct inode * inode;
1384         struct file * file;
1385         int retval = 0;
1386
1387         binfmt = current->binfmt;
1388         if (!binfmt || !binfmt->core_dump)
1389                 goto fail;
1390         down_write(&mm->mmap_sem);
1391         if (!mm->dumpable) {
1392                 up_write(&mm->mmap_sem);
1393                 goto fail;
1394         }
1395         mm->dumpable = 0;
1396         init_completion(&mm->core_done);
1397         current->signal->group_exit = 1;
1398         current->signal->group_exit_code = exit_code;
1399         coredump_wait(mm);
1400
1401         if (current->rlim[RLIMIT_CORE].rlim_cur < binfmt->min_coredump)
1402                 goto fail_unlock;
1403
1404         /*
1405          * lock_kernel() because format_corename() is controlled by sysctl, which
1406          * uses lock_kernel()
1407          */
1408         lock_kernel();
1409         format_corename(corename, core_pattern, signr);
1410         unlock_kernel();
1411         file = filp_open(corename, O_CREAT | 2 | O_NOFOLLOW | O_LARGEFILE, 0600);
1412         if (IS_ERR(file))
1413                 goto fail_unlock;
1414         inode = file->f_dentry->d_inode;
1415         if (inode->i_nlink > 1)
1416                 goto close_fail;        /* multiple links - don't dump */
1417         if (d_unhashed(file->f_dentry))
1418                 goto close_fail;
1419
1420         if (!S_ISREG(inode->i_mode))
1421                 goto close_fail;
1422         if (!file->f_op)
1423                 goto close_fail;
1424         if (!file->f_op->write)
1425                 goto close_fail;
1426         if (do_truncate(file->f_dentry, 0) != 0)
1427                 goto close_fail;
1428
1429         retval = binfmt->core_dump(signr, regs, file);
1430
1431         current->signal->group_exit_code |= 0x80;
1432 close_fail:
1433         filp_close(file, NULL);
1434 fail_unlock:
1435         complete_all(&mm->core_done);
1436 fail:
1437         return retval;
1438 }