Merge to VServer 1.9.0
[linux-2.6.git] / fs / exec.c
1 /*
2  *  linux/fs/exec.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6
7 /*
8  * #!-checking implemented by tytso.
9  */
10 /*
11  * Demand-loading implemented 01.12.91 - no need to read anything but
12  * the header into memory. The inode of the executable is put into
13  * "current->executable", and page faults do the actual loading. Clean.
14  *
15  * Once more I can proudly say that linux stood up to being changed: it
16  * was less than 2 hours work to get demand-loading completely implemented.
17  *
18  * Demand loading changed July 1993 by Eric Youngdale.   Use mmap instead,
19  * current->executable is only used by the procfs.  This allows a dispatch
20  * table to check for several different types  of binary formats.  We keep
21  * trying until we recognize the file or we run out of supported binary
22  * formats. 
23  */
24
25 #include <linux/config.h>
26 #include <linux/slab.h>
27 #include <linux/file.h>
28 #include <linux/mman.h>
29 #include <linux/a.out.h>
30 #include <linux/stat.h>
31 #include <linux/fcntl.h>
32 #include <linux/smp_lock.h>
33 #include <linux/init.h>
34 #include <linux/pagemap.h>
35 #include <linux/highmem.h>
36 #include <linux/spinlock.h>
37 #include <linux/personality.h>
38 #include <linux/binfmts.h>
39 #include <linux/swap.h>
40 #include <linux/utsname.h>
41 #include <linux/module.h>
42 #include <linux/namei.h>
43 #include <linux/proc_fs.h>
44 #include <linux/ptrace.h>
45 #include <linux/mount.h>
46 #include <linux/security.h>
47 #include <linux/syscalls.h>
48 #include <linux/rmap.h>
49
50 #include <asm/uaccess.h>
51 #include <asm/pgalloc.h>
52 #include <asm/mmu_context.h>
53
54 #ifdef CONFIG_KMOD
55 #include <linux/kmod.h>
56 #endif
57
58 int core_uses_pid;
59 char core_pattern[65] = "core";
60 /* The maximal length of core_pattern is also specified in sysctl.c */
61
62 static struct linux_binfmt *formats;
63 static rwlock_t binfmt_lock = RW_LOCK_UNLOCKED;
64
65 int register_binfmt(struct linux_binfmt * fmt)
66 {
67         struct linux_binfmt ** tmp = &formats;
68
69         if (!fmt)
70                 return -EINVAL;
71         if (fmt->next)
72                 return -EBUSY;
73         write_lock(&binfmt_lock);
74         while (*tmp) {
75                 if (fmt == *tmp) {
76                         write_unlock(&binfmt_lock);
77                         return -EBUSY;
78                 }
79                 tmp = &(*tmp)->next;
80         }
81         fmt->next = formats;
82         formats = fmt;
83         write_unlock(&binfmt_lock);
84         return 0;       
85 }
86
87 EXPORT_SYMBOL(register_binfmt);
88
89 int unregister_binfmt(struct linux_binfmt * fmt)
90 {
91         struct linux_binfmt ** tmp = &formats;
92
93         write_lock(&binfmt_lock);
94         while (*tmp) {
95                 if (fmt == *tmp) {
96                         *tmp = fmt->next;
97                         write_unlock(&binfmt_lock);
98                         return 0;
99                 }
100                 tmp = &(*tmp)->next;
101         }
102         write_unlock(&binfmt_lock);
103         return -EINVAL;
104 }
105
106 EXPORT_SYMBOL(unregister_binfmt);
107
108 static inline void put_binfmt(struct linux_binfmt * fmt)
109 {
110         module_put(fmt->module);
111 }
112
113 /*
114  * Note that a shared library must be both readable and executable due to
115  * security reasons.
116  *
117  * Also note that we take the address to load from from the file itself.
118  */
119 asmlinkage long sys_uselib(const char __user * library)
120 {
121         struct file * file;
122         struct nameidata nd;
123         int error;
124
125         nd.intent.open.flags = FMODE_READ;
126         error = __user_walk(library, LOOKUP_FOLLOW|LOOKUP_OPEN, &nd);
127         if (error)
128                 goto out;
129
130         error = -EINVAL;
131         if (!S_ISREG(nd.dentry->d_inode->i_mode))
132                 goto exit;
133
134         error = permission(nd.dentry->d_inode, MAY_READ | MAY_EXEC, &nd);
135         if (error)
136                 goto exit;
137
138         file = dentry_open(nd.dentry, nd.mnt, O_RDONLY);
139         error = PTR_ERR(file);
140         if (IS_ERR(file))
141                 goto out;
142
143         error = -ENOEXEC;
144         if(file->f_op) {
145                 struct linux_binfmt * fmt;
146
147                 read_lock(&binfmt_lock);
148                 for (fmt = formats ; fmt ; fmt = fmt->next) {
149                         if (!fmt->load_shlib)
150                                 continue;
151                         if (!try_module_get(fmt->module))
152                                 continue;
153                         read_unlock(&binfmt_lock);
154                         error = fmt->load_shlib(file);
155                         read_lock(&binfmt_lock);
156                         put_binfmt(fmt);
157                         if (error != -ENOEXEC)
158                                 break;
159                 }
160                 read_unlock(&binfmt_lock);
161         }
162         fput(file);
163 out:
164         return error;
165 exit:
166         path_release(&nd);
167         goto out;
168 }
169
170 /*
171  * count() counts the number of strings in array ARGV.
172  */
173 static int count(char __user * __user * argv, int max)
174 {
175         int i = 0;
176
177         if (argv != NULL) {
178                 for (;;) {
179                         char __user * p;
180
181                         if (get_user(p, argv))
182                                 return -EFAULT;
183                         if (!p)
184                                 break;
185                         argv++;
186                         if(++i > max)
187                                 return -E2BIG;
188                 }
189         }
190         return i;
191 }
192
193 /*
194  * 'copy_strings()' copies argument/environment strings from user
195  * memory to free pages in kernel mem. These are in a format ready
196  * to be put directly into the top of new user memory.
197  */
198 int copy_strings(int argc,char __user * __user * argv, struct linux_binprm *bprm)
199 {
200         struct page *kmapped_page = NULL;
201         char *kaddr = NULL;
202         int ret;
203
204         while (argc-- > 0) {
205                 char __user *str;
206                 int len;
207                 unsigned long pos;
208
209                 if (get_user(str, argv+argc) ||
210                                 !(len = strnlen_user(str, bprm->p))) {
211                         ret = -EFAULT;
212                         goto out;
213                 }
214
215                 if (bprm->p < len)  {
216                         ret = -E2BIG;
217                         goto out;
218                 }
219
220                 bprm->p -= len;
221                 /* XXX: add architecture specific overflow check here. */
222                 pos = bprm->p;
223
224                 while (len > 0) {
225                         int i, new, err;
226                         int offset, bytes_to_copy;
227                         struct page *page;
228
229                         offset = pos % PAGE_SIZE;
230                         i = pos/PAGE_SIZE;
231                         page = bprm->page[i];
232                         new = 0;
233                         if (!page) {
234                                 page = alloc_page(GFP_HIGHUSER);
235                                 bprm->page[i] = page;
236                                 if (!page) {
237                                         ret = -ENOMEM;
238                                         goto out;
239                                 }
240                                 new = 1;
241                         }
242
243                         if (page != kmapped_page) {
244                                 if (kmapped_page)
245                                         kunmap(kmapped_page);
246                                 kmapped_page = page;
247                                 kaddr = kmap(kmapped_page);
248                         }
249                         if (new && offset)
250                                 memset(kaddr, 0, offset);
251                         bytes_to_copy = PAGE_SIZE - offset;
252                         if (bytes_to_copy > len) {
253                                 bytes_to_copy = len;
254                                 if (new)
255                                         memset(kaddr+offset+len, 0,
256                                                 PAGE_SIZE-offset-len);
257                         }
258                         err = copy_from_user(kaddr+offset, str, bytes_to_copy);
259                         if (err) {
260                                 ret = -EFAULT;
261                                 goto out;
262                         }
263
264                         pos += bytes_to_copy;
265                         str += bytes_to_copy;
266                         len -= bytes_to_copy;
267                 }
268         }
269         ret = 0;
270 out:
271         if (kmapped_page)
272                 kunmap(kmapped_page);
273         return ret;
274 }
275
276 /*
277  * Like copy_strings, but get argv and its values from kernel memory.
278  */
279 int copy_strings_kernel(int argc,char ** argv, struct linux_binprm *bprm)
280 {
281         int r;
282         mm_segment_t oldfs = get_fs();
283         set_fs(KERNEL_DS);
284         r = copy_strings(argc, (char __user * __user *)argv, bprm);
285         set_fs(oldfs);
286         return r;
287 }
288
289 EXPORT_SYMBOL(copy_strings_kernel);
290
291 #ifdef CONFIG_MMU
292 /*
293  * This routine is used to map in a page into an address space: needed by
294  * execve() for the initial stack and environment pages.
295  *
296  * vma->vm_mm->mmap_sem is held for writing.
297  */
298 void install_arg_page(struct vm_area_struct *vma,
299                         struct page *page, unsigned long address)
300 {
301         struct mm_struct *mm = vma->vm_mm;
302         pgd_t * pgd;
303         pmd_t * pmd;
304         pte_t * pte;
305
306         if (unlikely(anon_vma_prepare(vma)))
307                 goto out_sig;
308
309         flush_dcache_page(page);
310         pgd = pgd_offset(mm, address);
311
312         spin_lock(&mm->page_table_lock);
313         pmd = pmd_alloc(mm, pgd, address);
314         if (!pmd)
315                 goto out;
316         pte = pte_alloc_map(mm, pmd, address);
317         if (!pte)
318                 goto out;
319         if (!pte_none(*pte)) {
320                 pte_unmap(pte);
321                 goto out;
322         }
323         // mm->rss++;
324         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_page_prot = protection_map[mpnt->vm_flags & 0x7];
442                 insert_vm_struct(mm, mpnt);
443                 // mm->total_vm = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT;
444                 vx_vmpages_sub(mm, mm->total_vm -
445                         ((mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT));
446         }
447
448         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
449                 struct page *page = bprm->page[i];
450                 if (page) {
451                         bprm->page[i] = NULL;
452                         install_arg_page(mpnt, page, stack_base);
453                 }
454                 stack_base += PAGE_SIZE;
455         }
456         up_write(&mm->mmap_sem);
457         
458         return 0;
459 }
460
461 EXPORT_SYMBOL(setup_arg_pages);
462
463 #define free_arg_pages(bprm) do { } while (0)
464
465 #else
466
467 static inline void free_arg_pages(struct linux_binprm *bprm)
468 {
469         int i;
470
471         for (i = 0; i < MAX_ARG_PAGES; i++) {
472                 if (bprm->page[i])
473                         __free_page(bprm->page[i]);
474                 bprm->page[i] = NULL;
475         }
476 }
477
478 #endif /* CONFIG_MMU */
479
480 struct file *open_exec(const char *name)
481 {
482         struct nameidata nd;
483         int err;
484         struct file *file;
485
486         nd.intent.open.flags = FMODE_READ;
487         err = path_lookup(name, LOOKUP_FOLLOW|LOOKUP_OPEN, &nd);
488         file = ERR_PTR(err);
489
490         if (!err) {
491                 struct inode *inode = nd.dentry->d_inode;
492                 file = ERR_PTR(-EACCES);
493                 if (!(nd.mnt->mnt_flags & MNT_NOEXEC) &&
494                     S_ISREG(inode->i_mode)) {
495                         int err = permission(inode, MAY_EXEC, &nd);
496                         if (!err && !(inode->i_mode & 0111))
497                                 err = -EACCES;
498                         file = ERR_PTR(err);
499                         if (!err) {
500                                 file = dentry_open(nd.dentry, nd.mnt, O_RDONLY);
501                                 if (!IS_ERR(file)) {
502                                         err = deny_write_access(file);
503                                         if (err) {
504                                                 fput(file);
505                                                 file = ERR_PTR(err);
506                                         }
507                                 }
508 out:
509                                 return file;
510                         }
511                 }
512                 path_release(&nd);
513         }
514         goto out;
515 }
516
517 EXPORT_SYMBOL(open_exec);
518
519 int kernel_read(struct file *file, unsigned long offset,
520         char *addr, unsigned long count)
521 {
522         mm_segment_t old_fs;
523         loff_t pos = offset;
524         int result;
525
526         old_fs = get_fs();
527         set_fs(get_ds());
528         /* The cast to a user pointer is valid due to the set_fs() */
529         result = vfs_read(file, (void __user *)addr, count, &pos);
530         set_fs(old_fs);
531         return result;
532 }
533
534 EXPORT_SYMBOL(kernel_read);
535
536 static int exec_mmap(struct mm_struct *mm)
537 {
538         struct task_struct *tsk;
539         struct mm_struct * old_mm, *active_mm;
540
541         /* Add it to the list of mm's */
542         spin_lock(&mmlist_lock);
543         list_add(&mm->mmlist, &init_mm.mmlist);
544         mmlist_nr++;
545         spin_unlock(&mmlist_lock);
546
547         /* Notify parent that we're no longer interested in the old VM */
548         tsk = current;
549         old_mm = current->mm;
550         mm_release(tsk, old_mm);
551
552         task_lock(tsk);
553         active_mm = tsk->active_mm;
554         tsk->mm = mm;
555         tsk->active_mm = mm;
556         activate_mm(active_mm, mm);
557         task_unlock(tsk);
558         if (old_mm) {
559                 if (active_mm != old_mm) BUG();
560                 mmput(old_mm);
561                 return 0;
562         }
563         mmdrop(active_mm);
564         return 0;
565 }
566
567 /*
568  * This function makes sure the current process has its own signal table,
569  * so that flush_signal_handlers can later reset the handlers without
570  * disturbing other processes.  (Other processes might share the signal
571  * table via the CLONE_SIGHAND option to clone().)
572  */
573 static inline int de_thread(struct task_struct *tsk)
574 {
575         struct signal_struct *newsig, *oldsig = tsk->signal;
576         struct sighand_struct *newsighand, *oldsighand = tsk->sighand;
577         spinlock_t *lock = &oldsighand->siglock;
578         int count;
579
580         /*
581          * If we don't share sighandlers, then we aren't sharing anything
582          * and we can just re-use it all.
583          */
584         if (atomic_read(&oldsighand->count) <= 1)
585                 return 0;
586
587         newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
588         if (!newsighand)
589                 return -ENOMEM;
590
591         spin_lock_init(&newsighand->siglock);
592         atomic_set(&newsighand->count, 1);
593         memcpy(newsighand->action, oldsighand->action, sizeof(newsighand->action));
594
595         /*
596          * See if we need to allocate a new signal structure
597          */
598         newsig = NULL;
599         if (atomic_read(&oldsig->count) > 1) {
600                 newsig = kmem_cache_alloc(signal_cachep, GFP_KERNEL);
601                 if (!newsig) {
602                         kmem_cache_free(sighand_cachep, newsighand);
603                         return -ENOMEM;
604                 }
605                 atomic_set(&newsig->count, 1);
606                 newsig->group_exit = 0;
607                 newsig->group_exit_code = 0;
608                 newsig->group_exit_task = NULL;
609                 newsig->group_stop_count = 0;
610                 newsig->curr_target = NULL;
611                 init_sigpending(&newsig->shared_pending);
612                 INIT_LIST_HEAD(&newsig->posix_timers);
613
614                 newsig->tty = oldsig->tty;
615                 newsig->pgrp = oldsig->pgrp;
616                 newsig->session = oldsig->session;
617                 newsig->leader = oldsig->leader;
618                 newsig->tty_old_pgrp = oldsig->tty_old_pgrp;
619         }
620
621         if (thread_group_empty(current))
622                 goto no_thread_group;
623
624         /*
625          * Kill all other threads in the thread group.
626          * We must hold tasklist_lock to call zap_other_threads.
627          */
628         read_lock(&tasklist_lock);
629         spin_lock_irq(lock);
630         if (oldsig->group_exit) {
631                 /*
632                  * Another group action in progress, just
633                  * return so that the signal is processed.
634                  */
635                 spin_unlock_irq(lock);
636                 read_unlock(&tasklist_lock);
637                 kmem_cache_free(sighand_cachep, newsighand);
638                 if (newsig)
639                         kmem_cache_free(signal_cachep, newsig);
640                 return -EAGAIN;
641         }
642         oldsig->group_exit = 1;
643         zap_other_threads(current);
644         read_unlock(&tasklist_lock);
645
646         /*
647          * Account for the thread group leader hanging around:
648          */
649         count = 2;
650         if (current->pid == current->tgid)
651                 count = 1;
652         while (atomic_read(&oldsig->count) > count) {
653                 oldsig->group_exit_task = current;
654                 oldsig->notify_count = count;
655                 __set_current_state(TASK_UNINTERRUPTIBLE);
656                 spin_unlock_irq(lock);
657                 schedule();
658                 spin_lock_irq(lock);
659         }
660         spin_unlock_irq(lock);
661
662         /*
663          * At this point all other threads have exited, all we have to
664          * do is to wait for the thread group leader to become inactive,
665          * and to assume its PID:
666          */
667         if (current->pid != current->tgid) {
668                 struct task_struct *leader = current->group_leader, *parent;
669                 struct dentry *proc_dentry1, *proc_dentry2;
670                 unsigned long state, ptrace;
671
672                 /*
673                  * Wait for the thread group leader to be a zombie.
674                  * It should already be zombie at this point, most
675                  * of the time.
676                  */
677                 while (leader->state != TASK_ZOMBIE)
678                         yield();
679
680                 spin_lock(&leader->proc_lock);
681                 spin_lock(&current->proc_lock);
682                 proc_dentry1 = proc_pid_unhash(current);
683                 proc_dentry2 = proc_pid_unhash(leader);
684                 write_lock_irq(&tasklist_lock);
685
686                 if (leader->tgid != current->tgid)
687                         BUG();
688                 if (current->pid == current->tgid)
689                         BUG();
690                 /*
691                  * An exec() starts a new thread group with the
692                  * TGID of the previous thread group. Rehash the
693                  * two threads with a switched PID, and release
694                  * the former thread group leader:
695                  */
696                 ptrace = leader->ptrace;
697                 parent = leader->parent;
698
699                 ptrace_unlink(current);
700                 ptrace_unlink(leader);
701                 remove_parent(current);
702                 remove_parent(leader);
703
704                 switch_exec_pids(leader, current);
705
706                 current->parent = current->real_parent = leader->real_parent;
707                 leader->parent = leader->real_parent = child_reaper;
708                 current->group_leader = current;
709                 leader->group_leader = leader;
710
711                 add_parent(current, current->parent);
712                 add_parent(leader, leader->parent);
713                 if (ptrace) {
714                         current->ptrace = ptrace;
715                         __ptrace_link(current, parent);
716                 }
717
718                 list_del(&current->tasks);
719                 list_add_tail(&current->tasks, &init_task.tasks);
720                 current->exit_signal = SIGCHLD;
721                 state = leader->state;
722
723                 write_unlock_irq(&tasklist_lock);
724                 spin_unlock(&leader->proc_lock);
725                 spin_unlock(&current->proc_lock);
726                 proc_pid_flush(proc_dentry1);
727                 proc_pid_flush(proc_dentry2);
728
729                 if (state != TASK_ZOMBIE)
730                         BUG();
731                 release_task(leader);
732         }
733
734 no_thread_group:
735
736         write_lock_irq(&tasklist_lock);
737         spin_lock(&oldsighand->siglock);
738         spin_lock(&newsighand->siglock);
739
740         if (current == oldsig->curr_target)
741                 oldsig->curr_target = next_thread(current);
742         if (newsig)
743                 current->signal = newsig;
744         current->sighand = newsighand;
745         init_sigpending(&current->pending);
746         recalc_sigpending();
747
748         spin_unlock(&newsighand->siglock);
749         spin_unlock(&oldsighand->siglock);
750         write_unlock_irq(&tasklist_lock);
751
752         if (newsig && atomic_dec_and_test(&oldsig->count))
753                 kmem_cache_free(signal_cachep, oldsig);
754
755         if (atomic_dec_and_test(&oldsighand->count))
756                 kmem_cache_free(sighand_cachep, oldsighand);
757
758         if (!thread_group_empty(current))
759                 BUG();
760         if (current->tgid != current->pid)
761                 BUG();
762         return 0;
763 }
764         
765 /*
766  * These functions flushes out all traces of the currently running executable
767  * so that a new one can be started
768  */
769
770 static inline void flush_old_files(struct files_struct * files)
771 {
772         long j = -1;
773
774         spin_lock(&files->file_lock);
775         for (;;) {
776                 unsigned long set, i;
777
778                 j++;
779                 i = j * __NFDBITS;
780                 if (i >= files->max_fds || i >= files->max_fdset)
781                         break;
782                 set = files->close_on_exec->fds_bits[j];
783                 if (!set)
784                         continue;
785                 files->close_on_exec->fds_bits[j] = 0;
786                 spin_unlock(&files->file_lock);
787                 for ( ; set ; i++,set >>= 1) {
788                         if (set & 1) {
789                                 sys_close(i);
790                         }
791                 }
792                 spin_lock(&files->file_lock);
793
794         }
795         spin_unlock(&files->file_lock);
796 }
797
798 int flush_old_exec(struct linux_binprm * bprm)
799 {
800         char * name;
801         int i, ch, retval;
802         struct files_struct *files;
803
804         /*
805          * Make sure we have a private signal table and that
806          * we are unassociated from the previous thread group.
807          */
808         retval = de_thread(current);
809         if (retval)
810                 goto out;
811
812         /*
813          * Make sure we have private file handles. Ask the
814          * fork helper to do the work for us and the exit
815          * helper to do the cleanup of the old one.
816          */
817         files = current->files;         /* refcounted so safe to hold */
818         retval = unshare_files();
819         if (retval)
820                 goto out;
821         /*
822          * Release all of the old mmap stuff
823          */
824         retval = exec_mmap(bprm->mm);
825         if (retval)
826                 goto mmap_failed;
827
828         bprm->mm = NULL;                /* We're using it now */
829
830         /* This is the point of no return */
831         steal_locks(files);
832         put_files_struct(files);
833
834         current->sas_ss_sp = current->sas_ss_size = 0;
835
836         if (current->euid == current->uid && current->egid == current->gid)
837                 current->mm->dumpable = 1;
838         name = bprm->filename;
839         for (i=0; (ch = *(name++)) != '\0';) {
840                 if (ch == '/')
841                         i = 0;
842                 else
843                         if (i < 15)
844                                 current->comm[i++] = ch;
845         }
846         current->comm[i] = '\0';
847
848         current->flags &= ~PF_RELOCEXEC;
849         flush_thread();
850
851         if (bprm->e_uid != current->euid || bprm->e_gid != current->egid || 
852             permission(bprm->file->f_dentry->d_inode,MAY_READ, NULL))
853                 current->mm->dumpable = 0;
854
855         /* An exec changes our domain. We are no longer part of the thread
856            group */
857
858         current->self_exec_id++;
859                         
860         flush_signal_handlers(current, 0);
861         flush_old_files(current->files);
862
863         return 0;
864
865 mmap_failed:
866         put_files_struct(current->files);
867         current->files = files;
868 out:
869         return retval;
870 }
871
872 EXPORT_SYMBOL(flush_old_exec);
873
874 /* 
875  * Fill the binprm structure from the inode. 
876  * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
877  */
878 int prepare_binprm(struct linux_binprm *bprm)
879 {
880         int mode;
881         struct inode * inode = bprm->file->f_dentry->d_inode;
882         int retval;
883
884         mode = inode->i_mode;
885         /*
886          * Check execute perms again - if the caller has CAP_DAC_OVERRIDE,
887          * vfs_permission lets a non-executable through
888          */
889         if (!(mode & 0111))     /* with at least _one_ execute bit set */
890                 return -EACCES;
891         if (bprm->file->f_op == NULL)
892                 return -EACCES;
893
894         bprm->e_uid = current->euid;
895         bprm->e_gid = current->egid;
896
897         if(!(bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)) {
898                 /* Set-uid? */
899                 if (mode & S_ISUID) {
900                         bprm->e_uid = inode->i_uid;
901 #ifdef __i386__
902                         /* reset personality */
903                         current->personality = PER_LINUX;
904 #endif
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                         bprm->e_gid = inode->i_gid;
915 #ifdef __i386__
916                         /* reset personality */
917                         current->personality = PER_LINUX;
918 #endif
919                 }
920         }
921
922         /* fill in binprm security blob */
923         retval = security_bprm_set(bprm);
924         if (retval)
925                 return retval;
926
927         memset(bprm->buf,0,BINPRM_BUF_SIZE);
928         return kernel_read(bprm->file,0,bprm->buf,BINPRM_BUF_SIZE);
929 }
930
931 EXPORT_SYMBOL(prepare_binprm);
932
933 static inline int unsafe_exec(struct task_struct *p)
934 {
935         int unsafe = 0;
936         if (p->ptrace & PT_PTRACED) {
937                 if (p->ptrace & PT_PTRACE_CAP)
938                         unsafe |= LSM_UNSAFE_PTRACE_CAP;
939                 else
940                         unsafe |= LSM_UNSAFE_PTRACE;
941         }
942         if (atomic_read(&p->fs->count) > 1 ||
943             atomic_read(&p->files->count) > 1 ||
944             atomic_read(&p->sighand->count) > 1)
945                 unsafe |= LSM_UNSAFE_SHARE;
946
947         return unsafe;
948 }
949
950 void compute_creds(struct linux_binprm *bprm)
951 {
952         int unsafe;
953         task_lock(current);
954         unsafe = unsafe_exec(current);
955         security_bprm_apply_creds(bprm, unsafe);
956         task_unlock(current);
957 }
958
959 EXPORT_SYMBOL(compute_creds);
960
961 void remove_arg_zero(struct linux_binprm *bprm)
962 {
963         if (bprm->argc) {
964                 unsigned long offset;
965                 char * kaddr;
966                 struct page *page;
967
968                 offset = bprm->p % PAGE_SIZE;
969                 goto inside;
970
971                 while (bprm->p++, *(kaddr+offset++)) {
972                         if (offset != PAGE_SIZE)
973                                 continue;
974                         offset = 0;
975                         kunmap_atomic(kaddr, KM_USER0);
976 inside:
977                         page = bprm->page[bprm->p/PAGE_SIZE];
978                         kaddr = kmap_atomic(page, KM_USER0);
979                 }
980                 kunmap_atomic(kaddr, KM_USER0);
981                 bprm->argc--;
982         }
983 }
984
985 EXPORT_SYMBOL(remove_arg_zero);
986
987 /*
988  * cycle the list of binary formats handler, until one recognizes the image
989  */
990 int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs)
991 {
992         int try,retval=0;
993         struct linux_binfmt *fmt;
994 #ifdef __alpha__
995         /* handle /sbin/loader.. */
996         {
997             struct exec * eh = (struct exec *) bprm->buf;
998
999             if (!bprm->loader && eh->fh.f_magic == 0x183 &&
1000                 (eh->fh.f_flags & 0x3000) == 0x3000)
1001             {
1002                 struct file * file;
1003                 unsigned long loader;
1004
1005                 allow_write_access(bprm->file);
1006                 fput(bprm->file);
1007                 bprm->file = NULL;
1008
1009                 loader = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1010
1011                 file = open_exec("/sbin/loader");
1012                 retval = PTR_ERR(file);
1013                 if (IS_ERR(file))
1014                         return retval;
1015
1016                 /* Remember if the application is TASO.  */
1017                 bprm->sh_bang = eh->ah.entry < 0x100000000UL;
1018
1019                 bprm->file = file;
1020                 bprm->loader = loader;
1021                 retval = prepare_binprm(bprm);
1022                 if (retval<0)
1023                         return retval;
1024                 /* should call search_binary_handler recursively here,
1025                    but it does not matter */
1026             }
1027         }
1028 #endif
1029         retval = security_bprm_check(bprm);
1030         if (retval)
1031                 return retval;
1032
1033         /* kernel module loader fixup */
1034         /* so we don't try to load run modprobe in kernel space. */
1035         set_fs(USER_DS);
1036         for (try=0; try<2; try++) {
1037                 read_lock(&binfmt_lock);
1038                 for (fmt = formats ; fmt ; fmt = fmt->next) {
1039                         int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
1040                         if (!fn)
1041                                 continue;
1042                         if (!try_module_get(fmt->module))
1043                                 continue;
1044                         read_unlock(&binfmt_lock);
1045                         retval = fn(bprm, regs);
1046                         if (retval >= 0) {
1047                                 put_binfmt(fmt);
1048                                 allow_write_access(bprm->file);
1049                                 if (bprm->file)
1050                                         fput(bprm->file);
1051                                 bprm->file = NULL;
1052                                 current->did_exec = 1;
1053                                 return retval;
1054                         }
1055                         read_lock(&binfmt_lock);
1056                         put_binfmt(fmt);
1057                         if (retval != -ENOEXEC || bprm->mm == NULL)
1058                                 break;
1059                         if (!bprm->file) {
1060                                 read_unlock(&binfmt_lock);
1061                                 return retval;
1062                         }
1063                 }
1064                 read_unlock(&binfmt_lock);
1065                 if (retval != -ENOEXEC || bprm->mm == NULL) {
1066                         break;
1067 #ifdef CONFIG_KMOD
1068                 }else{
1069 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
1070                         if (printable(bprm->buf[0]) &&
1071                             printable(bprm->buf[1]) &&
1072                             printable(bprm->buf[2]) &&
1073                             printable(bprm->buf[3]))
1074                                 break; /* -ENOEXEC */
1075                         request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
1076 #endif
1077                 }
1078         }
1079         return retval;
1080 }
1081
1082 EXPORT_SYMBOL(search_binary_handler);
1083
1084 /*
1085  * sys_execve() executes a new program.
1086  */
1087 int do_execve(char * filename,
1088         char __user *__user *argv,
1089         char __user *__user *envp,
1090         struct pt_regs * regs)
1091 {
1092         struct linux_binprm bprm;
1093         struct file *file;
1094         int retval;
1095         int i;
1096
1097         sched_balance_exec();
1098
1099         file = open_exec(filename);
1100
1101         retval = PTR_ERR(file);
1102         if (IS_ERR(file))
1103                 return retval;
1104
1105         bprm.p = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1106         memset(bprm.page, 0, MAX_ARG_PAGES*sizeof(bprm.page[0]));
1107
1108         bprm.file = file;
1109         bprm.filename = filename;
1110         bprm.interp = filename;
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 }