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