update to 2.6.9-rc1
[linux-flexiantxendom0-3.2.10.git] / fs / exec.c
1 /*
2  *  linux/fs/exec.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6
7 /*
8  * #!-checking implemented by tytso.
9  */
10 /*
11  * Demand-loading implemented 01.12.91 - no need to read anything but
12  * the header into memory. The inode of the executable is put into
13  * "current->executable", and page faults do the actual loading. Clean.
14  *
15  * Once more I can proudly say that linux stood up to being changed: it
16  * was less than 2 hours work to get demand-loading completely implemented.
17  *
18  * Demand loading changed July 1993 by Eric Youngdale.   Use mmap instead,
19  * current->executable is only used by the procfs.  This allows a dispatch
20  * table to check for several different types  of binary formats.  We keep
21  * trying until we recognize the file or we run out of supported binary
22  * formats. 
23  */
24
25 #include <linux/config.h>
26 #include <linux/slab.h>
27 #include <linux/file.h>
28 #include <linux/mman.h>
29 #include <linux/a.out.h>
30 #include <linux/stat.h>
31 #include <linux/fcntl.h>
32 #include <linux/smp_lock.h>
33 #include <linux/init.h>
34 #include <linux/pagemap.h>
35 #include <linux/highmem.h>
36 #include <linux/spinlock.h>
37 #include <linux/personality.h>
38 #include <linux/binfmts.h>
39 #include <linux/swap.h>
40 #include <linux/utsname.h>
41 #include <linux/module.h>
42 #include <linux/namei.h>
43 #include <linux/proc_fs.h>
44 #include <linux/ptrace.h>
45 #include <linux/mount.h>
46 #include <linux/security.h>
47 #include <linux/syscalls.h>
48 #include <linux/rmap.h>
49
50 #include <asm/uaccess.h>
51 #include <asm/mmu_context.h>
52
53 #ifdef CONFIG_KMOD
54 #include <linux/kmod.h>
55 #endif
56
57 int core_uses_pid;
58 char core_pattern[65] = "core";
59 /* The maximal length of core_pattern is also specified in sysctl.c */
60
61 static struct linux_binfmt *formats;
62 static rwlock_t binfmt_lock = RW_LOCK_UNLOCKED;
63
64 int register_binfmt(struct linux_binfmt * fmt)
65 {
66         struct linux_binfmt ** tmp = &formats;
67
68         if (!fmt)
69                 return -EINVAL;
70         if (fmt->next)
71                 return -EBUSY;
72         write_lock(&binfmt_lock);
73         while (*tmp) {
74                 if (fmt == *tmp) {
75                         write_unlock(&binfmt_lock);
76                         return -EBUSY;
77                 }
78                 tmp = &(*tmp)->next;
79         }
80         fmt->next = formats;
81         formats = fmt;
82         write_unlock(&binfmt_lock);
83         return 0;       
84 }
85
86 EXPORT_SYMBOL(register_binfmt);
87
88 int unregister_binfmt(struct linux_binfmt * fmt)
89 {
90         struct linux_binfmt ** tmp = &formats;
91
92         write_lock(&binfmt_lock);
93         while (*tmp) {
94                 if (fmt == *tmp) {
95                         *tmp = fmt->next;
96                         write_unlock(&binfmt_lock);
97                         return 0;
98                 }
99                 tmp = &(*tmp)->next;
100         }
101         write_unlock(&binfmt_lock);
102         return -EINVAL;
103 }
104
105 EXPORT_SYMBOL(unregister_binfmt);
106
107 static inline void put_binfmt(struct linux_binfmt * fmt)
108 {
109         module_put(fmt->module);
110 }
111
112 /*
113  * Note that a shared library must be both readable and executable due to
114  * security reasons.
115  *
116  * Also note that we take the address to load from from the file itself.
117  */
118 asmlinkage long sys_uselib(const char __user * library)
119 {
120         struct file * file;
121         struct nameidata nd;
122         int error;
123
124         nd.intent.open.flags = FMODE_READ;
125         error = __user_walk(library, LOOKUP_FOLLOW|LOOKUP_OPEN, &nd);
126         if (error)
127                 goto out;
128
129         error = -EINVAL;
130         if (!S_ISREG(nd.dentry->d_inode->i_mode))
131                 goto exit;
132
133         error = permission(nd.dentry->d_inode, MAY_READ | MAY_EXEC, &nd);
134         if (error)
135                 goto exit;
136
137         file = dentry_open(nd.dentry, nd.mnt, O_RDONLY);
138         error = PTR_ERR(file);
139         if (IS_ERR(file))
140                 goto out;
141
142         error = -ENOEXEC;
143         if(file->f_op) {
144                 struct linux_binfmt * fmt;
145
146                 read_lock(&binfmt_lock);
147                 for (fmt = formats ; fmt ; fmt = fmt->next) {
148                         if (!fmt->load_shlib)
149                                 continue;
150                         if (!try_module_get(fmt->module))
151                                 continue;
152                         read_unlock(&binfmt_lock);
153                         error = fmt->load_shlib(file);
154                         read_lock(&binfmt_lock);
155                         put_binfmt(fmt);
156                         if (error != -ENOEXEC)
157                                 break;
158                 }
159                 read_unlock(&binfmt_lock);
160         }
161         fput(file);
162 out:
163         return error;
164 exit:
165         path_release(&nd);
166         goto out;
167 }
168
169 /*
170  * count() counts the number of strings in array ARGV.
171  */
172 static int count(char __user * __user * argv, int max)
173 {
174         int i = 0;
175
176         if (argv != NULL) {
177                 for (;;) {
178                         char __user * p;
179
180                         if (get_user(p, argv))
181                                 return -EFAULT;
182                         if (!p)
183                                 break;
184                         argv++;
185                         if(++i > max)
186                                 return -E2BIG;
187                 }
188         }
189         return i;
190 }
191
192 /*
193  * 'copy_strings()' copies argument/environment strings from user
194  * memory to free pages in kernel mem. These are in a format ready
195  * to be put directly into the top of new user memory.
196  */
197 int copy_strings(int argc,char __user * __user * argv, struct linux_binprm *bprm)
198 {
199         struct page *kmapped_page = NULL;
200         char *kaddr = NULL;
201         int ret;
202
203         while (argc-- > 0) {
204                 char __user *str;
205                 int len;
206                 unsigned long pos;
207
208                 if (get_user(str, argv+argc) ||
209                                 !(len = strnlen_user(str, bprm->p))) {
210                         ret = -EFAULT;
211                         goto out;
212                 }
213
214                 if (bprm->p < len)  {
215                         ret = -E2BIG;
216                         goto out;
217                 }
218
219                 bprm->p -= len;
220                 /* XXX: add architecture specific overflow check here. */
221                 pos = bprm->p;
222
223                 while (len > 0) {
224                         int i, new, err;
225                         int offset, bytes_to_copy;
226                         struct page *page;
227
228                         offset = pos % PAGE_SIZE;
229                         i = pos/PAGE_SIZE;
230                         page = bprm->page[i];
231                         new = 0;
232                         if (!page) {
233                                 page = alloc_page(GFP_HIGHUSER);
234                                 bprm->page[i] = page;
235                                 if (!page) {
236                                         ret = -ENOMEM;
237                                         goto out;
238                                 }
239                                 new = 1;
240                         }
241
242                         if (page != kmapped_page) {
243                                 if (kmapped_page)
244                                         kunmap(kmapped_page);
245                                 kmapped_page = page;
246                                 kaddr = kmap(kmapped_page);
247                         }
248                         if (new && offset)
249                                 memset(kaddr, 0, offset);
250                         bytes_to_copy = PAGE_SIZE - offset;
251                         if (bytes_to_copy > len) {
252                                 bytes_to_copy = len;
253                                 if (new)
254                                         memset(kaddr+offset+len, 0,
255                                                 PAGE_SIZE-offset-len);
256                         }
257                         err = copy_from_user(kaddr+offset, str, bytes_to_copy);
258                         if (err) {
259                                 ret = -EFAULT;
260                                 goto out;
261                         }
262
263                         pos += bytes_to_copy;
264                         str += bytes_to_copy;
265                         len -= bytes_to_copy;
266                 }
267         }
268         ret = 0;
269 out:
270         if (kmapped_page)
271                 kunmap(kmapped_page);
272         return ret;
273 }
274
275 /*
276  * Like copy_strings, but get argv and its values from kernel memory.
277  */
278 int copy_strings_kernel(int argc,char ** argv, struct linux_binprm *bprm)
279 {
280         int r;
281         mm_segment_t oldfs = get_fs();
282         set_fs(KERNEL_DS);
283         r = copy_strings(argc, (char __user * __user *)argv, bprm);
284         set_fs(oldfs);
285         return r;
286 }
287
288 EXPORT_SYMBOL(copy_strings_kernel);
289
290 #ifdef CONFIG_MMU
291 /*
292  * This routine is used to map in a page into an address space: needed by
293  * execve() for the initial stack and environment pages.
294  *
295  * vma->vm_mm->mmap_sem is held for writing.
296  */
297 void install_arg_page(struct vm_area_struct *vma,
298                         struct page *page, unsigned long address)
299 {
300         struct mm_struct *mm = vma->vm_mm;
301         pgd_t * pgd;
302         pmd_t * pmd;
303         pte_t * pte;
304
305         if (unlikely(anon_vma_prepare(vma)))
306                 goto out_sig;
307
308         flush_dcache_page(page);
309         pgd = pgd_offset(mm, address);
310
311         spin_lock(&mm->page_table_lock);
312         pmd = pmd_alloc(mm, pgd, address);
313         if (!pmd)
314                 goto out;
315         pte = pte_alloc_map(mm, pmd, address);
316         if (!pte)
317                 goto out;
318         if (!pte_none(*pte)) {
319                 pte_unmap(pte);
320                 goto out;
321         }
322         mm->rss++;
323         lru_cache_add_active(page);
324         set_pte(pte, pte_mkdirty(pte_mkwrite(mk_pte(
325                                         page, vma->vm_page_prot))));
326         page_add_anon_rmap(page, vma, address);
327         pte_unmap(pte);
328         spin_unlock(&mm->page_table_lock);
329
330         /* no need for flush_tlb */
331         return;
332 out:
333         spin_unlock(&mm->page_table_lock);
334 out_sig:
335         __free_page(page);
336         force_sig(SIGKILL, current);
337 }
338
339 int setup_arg_pages(struct linux_binprm *bprm, int executable_stack)
340 {
341         unsigned long stack_base;
342         struct vm_area_struct *mpnt;
343         struct mm_struct *mm = current->mm;
344         int i;
345         long arg_size;
346
347 #ifdef CONFIG_STACK_GROWSUP
348         /* Move the argument and environment strings to the bottom of the
349          * stack space.
350          */
351         int offset, j;
352         char *to, *from;
353
354         /* Start by shifting all the pages down */
355         i = 0;
356         for (j = 0; j < MAX_ARG_PAGES; j++) {
357                 struct page *page = bprm->page[j];
358                 if (!page)
359                         continue;
360                 bprm->page[i++] = page;
361         }
362
363         /* Now move them within their pages */
364         offset = bprm->p % PAGE_SIZE;
365         to = kmap(bprm->page[0]);
366         for (j = 1; j < i; j++) {
367                 memmove(to, to + offset, PAGE_SIZE - offset);
368                 from = kmap(bprm->page[j]);
369                 memcpy(to + PAGE_SIZE - offset, from, offset);
370                 kunmap(bprm->page[j - 1]);
371                 to = from;
372         }
373         memmove(to, to + offset, PAGE_SIZE - offset);
374         kunmap(bprm->page[j - 1]);
375
376         /* Adjust bprm->p to point to the end of the strings. */
377         bprm->p = PAGE_SIZE * i - offset;
378
379         /* Limit stack size to 1GB */
380         stack_base = current->rlim[RLIMIT_STACK].rlim_max;
381         if (stack_base > (1 << 30))
382                 stack_base = 1 << 30;
383         stack_base = PAGE_ALIGN(STACK_TOP - stack_base);
384
385         mm->arg_start = stack_base;
386         arg_size = i << PAGE_SHIFT;
387
388         /* zero pages that were copied above */
389         while (i < MAX_ARG_PAGES)
390                 bprm->page[i++] = NULL;
391 #else
392         stack_base = STACK_TOP - MAX_ARG_PAGES * PAGE_SIZE;
393         mm->arg_start = bprm->p + stack_base;
394         arg_size = STACK_TOP - (PAGE_MASK & (unsigned long) mm->arg_start);
395 #endif
396
397         bprm->p += stack_base;
398         if (bprm->loader)
399                 bprm->loader += stack_base;
400         bprm->exec += stack_base;
401
402         mpnt = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
403         if (!mpnt)
404                 return -ENOMEM;
405
406         if (security_vm_enough_memory(arg_size >> PAGE_SHIFT)) {
407                 kmem_cache_free(vm_area_cachep, mpnt);
408                 return -ENOMEM;
409         }
410
411         memset(mpnt, 0, sizeof(*mpnt));
412
413         down_write(&mm->mmap_sem);
414         {
415                 mpnt->vm_mm = mm;
416 #ifdef CONFIG_STACK_GROWSUP
417                 mpnt->vm_start = stack_base;
418                 mpnt->vm_end = PAGE_MASK &
419                         (PAGE_SIZE - 1 + (unsigned long) bprm->p);
420 #else
421                 mpnt->vm_start = PAGE_MASK & (unsigned long) bprm->p;
422                 mpnt->vm_end = STACK_TOP;
423 #endif
424                 /* Adjust stack execute permissions; explicitly enable
425                  * for EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X
426                  * and leave alone (arch default) otherwise. */
427                 if (unlikely(executable_stack == EXSTACK_ENABLE_X))
428                         mpnt->vm_flags = VM_STACK_FLAGS |  VM_EXEC;
429                 else if (executable_stack == EXSTACK_DISABLE_X)
430                         mpnt->vm_flags = VM_STACK_FLAGS & ~VM_EXEC;
431                 else
432                         mpnt->vm_flags = VM_STACK_FLAGS;
433                 mpnt->vm_flags |= mm->def_flags;
434                 mpnt->vm_page_prot = protection_map[mpnt->vm_flags & 0x7];
435                 insert_vm_struct(mm, mpnt);
436                 mm->total_vm = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT;
437         }
438
439         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
440                 struct page *page = bprm->page[i];
441                 if (page) {
442                         bprm->page[i] = NULL;
443                         install_arg_page(mpnt, page, stack_base);
444                 }
445                 stack_base += PAGE_SIZE;
446         }
447         up_write(&mm->mmap_sem);
448         
449         return 0;
450 }
451
452 EXPORT_SYMBOL(setup_arg_pages);
453
454 #define free_arg_pages(bprm) do { } while (0)
455
456 #else
457
458 static inline void free_arg_pages(struct linux_binprm *bprm)
459 {
460         int i;
461
462         for (i = 0; i < MAX_ARG_PAGES; i++) {
463                 if (bprm->page[i])
464                         __free_page(bprm->page[i]);
465                 bprm->page[i] = NULL;
466         }
467 }
468
469 #endif /* CONFIG_MMU */
470
471 struct file *open_exec(const char *name)
472 {
473         struct nameidata nd;
474         int err;
475         struct file *file;
476
477         nd.intent.open.flags = FMODE_READ;
478         err = path_lookup(name, LOOKUP_FOLLOW|LOOKUP_OPEN, &nd);
479         file = ERR_PTR(err);
480
481         if (!err) {
482                 struct inode *inode = nd.dentry->d_inode;
483                 file = ERR_PTR(-EACCES);
484                 if (!(nd.mnt->mnt_flags & MNT_NOEXEC) &&
485                     S_ISREG(inode->i_mode)) {
486                         int err = permission(inode, MAY_EXEC, &nd);
487                         if (!err && !(inode->i_mode & 0111))
488                                 err = -EACCES;
489                         file = ERR_PTR(err);
490                         if (!err) {
491                                 file = dentry_open(nd.dentry, nd.mnt, O_RDONLY);
492                                 if (!IS_ERR(file)) {
493                                         err = deny_write_access(file);
494                                         if (err) {
495                                                 fput(file);
496                                                 file = ERR_PTR(err);
497                                         }
498                                 }
499 out:
500                                 return file;
501                         }
502                 }
503                 path_release(&nd);
504         }
505         goto out;
506 }
507
508 EXPORT_SYMBOL(open_exec);
509
510 int kernel_read(struct file *file, unsigned long offset,
511         char *addr, unsigned long count)
512 {
513         mm_segment_t old_fs;
514         loff_t pos = offset;
515         int result;
516
517         old_fs = get_fs();
518         set_fs(get_ds());
519         /* The cast to a user pointer is valid due to the set_fs() */
520         result = vfs_read(file, (void __user *)addr, count, &pos);
521         set_fs(old_fs);
522         return result;
523 }
524
525 EXPORT_SYMBOL(kernel_read);
526
527 static int exec_mmap(struct mm_struct *mm)
528 {
529         struct task_struct *tsk;
530         struct mm_struct * old_mm, *active_mm;
531
532         /* Add it to the list of mm's */
533         spin_lock(&mmlist_lock);
534         list_add(&mm->mmlist, &init_mm.mmlist);
535         mmlist_nr++;
536         spin_unlock(&mmlist_lock);
537
538         /* Notify parent that we're no longer interested in the old VM */
539         tsk = current;
540         old_mm = current->mm;
541         mm_release(tsk, old_mm);
542
543         task_lock(tsk);
544         active_mm = tsk->active_mm;
545         tsk->mm = mm;
546         tsk->active_mm = mm;
547         activate_mm(active_mm, mm);
548         task_unlock(tsk);
549         if (old_mm) {
550                 if (active_mm != old_mm) BUG();
551                 mmput(old_mm);
552                 return 0;
553         }
554         mmdrop(active_mm);
555         return 0;
556 }
557
558 /*
559  * This function makes sure the current process has its own signal table,
560  * so that flush_signal_handlers can later reset the handlers without
561  * disturbing other processes.  (Other processes might share the signal
562  * table via the CLONE_SIGHAND option to clone().)
563  */
564 static inline int de_thread(struct task_struct *tsk)
565 {
566         struct signal_struct *newsig, *oldsig = tsk->signal;
567         struct sighand_struct *newsighand, *oldsighand = tsk->sighand;
568         spinlock_t *lock = &oldsighand->siglock;
569         int count;
570
571         /*
572          * If we don't share sighandlers, then we aren't sharing anything
573          * and we can just re-use it all.
574          */
575         if (atomic_read(&oldsighand->count) <= 1)
576                 return 0;
577
578         newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
579         if (!newsighand)
580                 return -ENOMEM;
581
582         spin_lock_init(&newsighand->siglock);
583         atomic_set(&newsighand->count, 1);
584         memcpy(newsighand->action, oldsighand->action, sizeof(newsighand->action));
585
586         /*
587          * See if we need to allocate a new signal structure
588          */
589         newsig = NULL;
590         if (atomic_read(&oldsig->count) > 1) {
591                 newsig = kmem_cache_alloc(signal_cachep, GFP_KERNEL);
592                 if (!newsig) {
593                         kmem_cache_free(sighand_cachep, newsighand);
594                         return -ENOMEM;
595                 }
596                 atomic_set(&newsig->count, 1);
597                 newsig->group_exit = 0;
598                 newsig->group_exit_code = 0;
599                 newsig->group_exit_task = NULL;
600                 newsig->group_stop_count = 0;
601                 newsig->curr_target = NULL;
602                 init_sigpending(&newsig->shared_pending);
603                 INIT_LIST_HEAD(&newsig->posix_timers);
604
605                 newsig->tty = oldsig->tty;
606                 newsig->pgrp = oldsig->pgrp;
607                 newsig->session = oldsig->session;
608                 newsig->leader = oldsig->leader;
609                 newsig->tty_old_pgrp = oldsig->tty_old_pgrp;
610         }
611
612         if (thread_group_empty(current))
613                 goto no_thread_group;
614
615         /*
616          * Kill all other threads in the thread group.
617          * We must hold tasklist_lock to call zap_other_threads.
618          */
619         read_lock(&tasklist_lock);
620         spin_lock_irq(lock);
621         if (oldsig->group_exit) {
622                 /*
623                  * Another group action in progress, just
624                  * return so that the signal is processed.
625                  */
626                 spin_unlock_irq(lock);
627                 read_unlock(&tasklist_lock);
628                 kmem_cache_free(sighand_cachep, newsighand);
629                 if (newsig)
630                         kmem_cache_free(signal_cachep, newsig);
631                 return -EAGAIN;
632         }
633         oldsig->group_exit = 1;
634         zap_other_threads(current);
635         read_unlock(&tasklist_lock);
636
637         /*
638          * Account for the thread group leader hanging around:
639          */
640         count = 2;
641         if (current->pid == current->tgid)
642                 count = 1;
643         while (atomic_read(&oldsig->count) > count) {
644                 oldsig->group_exit_task = current;
645                 oldsig->notify_count = count;
646                 __set_current_state(TASK_UNINTERRUPTIBLE);
647                 spin_unlock_irq(lock);
648                 schedule();
649                 spin_lock_irq(lock);
650         }
651         spin_unlock_irq(lock);
652
653         /*
654          * At this point all other threads have exited, all we have to
655          * do is to wait for the thread group leader to become inactive,
656          * and to assume its PID:
657          */
658         if (current->pid != current->tgid) {
659                 struct task_struct *leader = current->group_leader, *parent;
660                 struct dentry *proc_dentry1, *proc_dentry2;
661                 unsigned long state, ptrace;
662
663                 /*
664                  * Wait for the thread group leader to be a zombie.
665                  * It should already be zombie at this point, most
666                  * of the time.
667                  */
668                 while (leader->state != TASK_ZOMBIE)
669                         yield();
670
671                 spin_lock(&leader->proc_lock);
672                 spin_lock(&current->proc_lock);
673                 proc_dentry1 = proc_pid_unhash(current);
674                 proc_dentry2 = proc_pid_unhash(leader);
675                 write_lock_irq(&tasklist_lock);
676
677                 if (leader->tgid != current->tgid)
678                         BUG();
679                 if (current->pid == current->tgid)
680                         BUG();
681                 /*
682                  * An exec() starts a new thread group with the
683                  * TGID of the previous thread group. Rehash the
684                  * two threads with a switched PID, and release
685                  * the former thread group leader:
686                  */
687                 ptrace = leader->ptrace;
688                 parent = leader->parent;
689
690                 ptrace_unlink(current);
691                 ptrace_unlink(leader);
692                 remove_parent(current);
693                 remove_parent(leader);
694
695                 switch_exec_pids(leader, current);
696
697                 current->parent = current->real_parent = leader->real_parent;
698                 leader->parent = leader->real_parent = child_reaper;
699                 current->group_leader = current;
700                 leader->group_leader = leader;
701
702                 add_parent(current, current->parent);
703                 add_parent(leader, leader->parent);
704                 if (ptrace) {
705                         current->ptrace = ptrace;
706                         __ptrace_link(current, parent);
707                 }
708
709                 list_del(&current->tasks);
710                 list_add_tail(&current->tasks, &init_task.tasks);
711                 current->exit_signal = SIGCHLD;
712                 state = leader->state;
713
714                 write_unlock_irq(&tasklist_lock);
715                 spin_unlock(&leader->proc_lock);
716                 spin_unlock(&current->proc_lock);
717                 proc_pid_flush(proc_dentry1);
718                 proc_pid_flush(proc_dentry2);
719
720                 if (state != TASK_ZOMBIE)
721                         BUG();
722                 release_task(leader);
723         }
724
725 no_thread_group:
726
727         write_lock_irq(&tasklist_lock);
728         spin_lock(&oldsighand->siglock);
729         spin_lock(&newsighand->siglock);
730
731         if (current == oldsig->curr_target)
732                 oldsig->curr_target = next_thread(current);
733         if (newsig)
734                 current->signal = newsig;
735         current->sighand = newsighand;
736         init_sigpending(&current->pending);
737         recalc_sigpending();
738
739         spin_unlock(&newsighand->siglock);
740         spin_unlock(&oldsighand->siglock);
741         write_unlock_irq(&tasklist_lock);
742
743         if (newsig && atomic_dec_and_test(&oldsig->count))
744                 kmem_cache_free(signal_cachep, oldsig);
745
746         if (atomic_dec_and_test(&oldsighand->count))
747                 kmem_cache_free(sighand_cachep, oldsighand);
748
749         if (!thread_group_empty(current))
750                 BUG();
751         if (current->tgid != current->pid)
752                 BUG();
753         return 0;
754 }
755         
756 /*
757  * These functions flushes out all traces of the currently running executable
758  * so that a new one can be started
759  */
760
761 static inline void flush_old_files(struct files_struct * files)
762 {
763         long j = -1;
764
765         spin_lock(&files->file_lock);
766         for (;;) {
767                 unsigned long set, i;
768
769                 j++;
770                 i = j * __NFDBITS;
771                 if (i >= files->max_fds || i >= files->max_fdset)
772                         break;
773                 set = files->close_on_exec->fds_bits[j];
774                 if (!set)
775                         continue;
776                 files->close_on_exec->fds_bits[j] = 0;
777                 spin_unlock(&files->file_lock);
778                 for ( ; set ; i++,set >>= 1) {
779                         if (set & 1) {
780                                 sys_close(i);
781                         }
782                 }
783                 spin_lock(&files->file_lock);
784
785         }
786         spin_unlock(&files->file_lock);
787 }
788
789 void get_task_comm(char *buf, struct task_struct *tsk)
790 {
791         /* buf must be at least sizeof(tsk->comm) in size */
792         task_lock(tsk);
793         memcpy(buf, tsk->comm, sizeof(tsk->comm));
794         task_unlock(tsk);
795 }
796
797 void set_task_comm(struct task_struct *tsk, char *buf)
798 {
799         task_lock(tsk);
800         strlcpy(tsk->comm, buf, sizeof(tsk->comm));
801         task_unlock(tsk);
802 }
803
804 int flush_old_exec(struct linux_binprm * bprm)
805 {
806         char * name;
807         int i, ch, retval;
808         struct files_struct *files;
809         char tcomm[sizeof(current->comm)];
810
811         /*
812          * Make sure we have a private signal table and that
813          * we are unassociated from the previous thread group.
814          */
815         retval = de_thread(current);
816         if (retval)
817                 goto out;
818
819         /*
820          * Make sure we have private file handles. Ask the
821          * fork helper to do the work for us and the exit
822          * helper to do the cleanup of the old one.
823          */
824         files = current->files;         /* refcounted so safe to hold */
825         retval = unshare_files();
826         if (retval)
827                 goto out;
828         /*
829          * Release all of the old mmap stuff
830          */
831         retval = exec_mmap(bprm->mm);
832         if (retval)
833                 goto mmap_failed;
834
835         bprm->mm = NULL;                /* We're using it now */
836
837         /* This is the point of no return */
838         steal_locks(files);
839         put_files_struct(files);
840
841         current->sas_ss_sp = current->sas_ss_size = 0;
842
843         if (current->euid == current->uid && current->egid == current->gid)
844                 current->mm->dumpable = 1;
845         name = bprm->filename;
846         for (i=0; (ch = *(name++)) != '\0';) {
847                 if (ch == '/')
848                         i = 0;
849                 else
850                         if (i < (sizeof(tcomm) - 1))
851                                 tcomm[i++] = ch;
852         }
853         tcomm[i] = '\0';
854         set_task_comm(current, tcomm);
855
856         flush_thread();
857
858         if (bprm->e_uid != current->euid || bprm->e_gid != current->egid || 
859             permission(bprm->file->f_dentry->d_inode,MAY_READ, NULL) ||
860             (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP))
861                 current->mm->dumpable = 0;
862
863         /* An exec changes our domain. We are no longer part of the thread
864            group */
865
866         current->self_exec_id++;
867                         
868         flush_signal_handlers(current, 0);
869         flush_old_files(current->files);
870
871         return 0;
872
873 mmap_failed:
874         put_files_struct(current->files);
875         current->files = files;
876 out:
877         return retval;
878 }
879
880 EXPORT_SYMBOL(flush_old_exec);
881
882 /* 
883  * Fill the binprm structure from the inode. 
884  * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
885  */
886 int prepare_binprm(struct linux_binprm *bprm)
887 {
888         int mode;
889         struct inode * inode = bprm->file->f_dentry->d_inode;
890         int retval;
891
892         mode = inode->i_mode;
893         /*
894          * Check execute perms again - if the caller has CAP_DAC_OVERRIDE,
895          * vfs_permission lets a non-executable through
896          */
897         if (!(mode & 0111))     /* with at least _one_ execute bit set */
898                 return -EACCES;
899         if (bprm->file->f_op == NULL)
900                 return -EACCES;
901
902         bprm->e_uid = current->euid;
903         bprm->e_gid = current->egid;
904
905         if(!(bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)) {
906                 /* Set-uid? */
907                 if (mode & S_ISUID) {
908                         current->personality &= ~PER_CLEAR_ON_SETID;
909                         bprm->e_uid = inode->i_uid;
910                 }
911
912                 /* Set-gid? */
913                 /*
914                  * If setgid is set but no group execute bit then this
915                  * is a candidate for mandatory locking, not a setgid
916                  * executable.
917                  */
918                 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
919                         current->personality &= ~PER_CLEAR_ON_SETID;
920                         bprm->e_gid = inode->i_gid;
921                 }
922         }
923
924         /* fill in binprm security blob */
925         retval = security_bprm_set(bprm);
926         if (retval)
927                 return retval;
928
929         memset(bprm->buf,0,BINPRM_BUF_SIZE);
930         return kernel_read(bprm->file,0,bprm->buf,BINPRM_BUF_SIZE);
931 }
932
933 EXPORT_SYMBOL(prepare_binprm);
934
935 static inline int unsafe_exec(struct task_struct *p)
936 {
937         int unsafe = 0;
938         if (p->ptrace & PT_PTRACED) {
939                 if (p->ptrace & PT_PTRACE_CAP)
940                         unsafe |= LSM_UNSAFE_PTRACE_CAP;
941                 else
942                         unsafe |= LSM_UNSAFE_PTRACE;
943         }
944         if (atomic_read(&p->fs->count) > 1 ||
945             atomic_read(&p->files->count) > 1 ||
946             atomic_read(&p->sighand->count) > 1)
947                 unsafe |= LSM_UNSAFE_SHARE;
948
949         return unsafe;
950 }
951
952 void compute_creds(struct linux_binprm *bprm)
953 {
954         int unsafe;
955         task_lock(current);
956         unsafe = unsafe_exec(current);
957         security_bprm_apply_creds(bprm, unsafe);
958         task_unlock(current);
959 }
960
961 EXPORT_SYMBOL(compute_creds);
962
963 void remove_arg_zero(struct linux_binprm *bprm)
964 {
965         if (bprm->argc) {
966                 unsigned long offset;
967                 char * kaddr;
968                 struct page *page;
969
970                 offset = bprm->p % PAGE_SIZE;
971                 goto inside;
972
973                 while (bprm->p++, *(kaddr+offset++)) {
974                         if (offset != PAGE_SIZE)
975                                 continue;
976                         offset = 0;
977                         kunmap_atomic(kaddr, KM_USER0);
978 inside:
979                         page = bprm->page[bprm->p/PAGE_SIZE];
980                         kaddr = kmap_atomic(page, KM_USER0);
981                 }
982                 kunmap_atomic(kaddr, KM_USER0);
983                 bprm->argc--;
984         }
985 }
986
987 EXPORT_SYMBOL(remove_arg_zero);
988
989 /*
990  * cycle the list of binary formats handler, until one recognizes the image
991  */
992 int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs)
993 {
994         int try,retval=0;
995         struct linux_binfmt *fmt;
996 #ifdef __alpha__
997         /* handle /sbin/loader.. */
998         {
999             struct exec * eh = (struct exec *) bprm->buf;
1000
1001             if (!bprm->loader && eh->fh.f_magic == 0x183 &&
1002                 (eh->fh.f_flags & 0x3000) == 0x3000)
1003             {
1004                 struct file * file;
1005                 unsigned long loader;
1006
1007                 allow_write_access(bprm->file);
1008                 fput(bprm->file);
1009                 bprm->file = NULL;
1010
1011                 loader = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1012
1013                 file = open_exec("/sbin/loader");
1014                 retval = PTR_ERR(file);
1015                 if (IS_ERR(file))
1016                         return retval;
1017
1018                 /* Remember if the application is TASO.  */
1019                 bprm->sh_bang = eh->ah.entry < 0x100000000UL;
1020
1021                 bprm->file = file;
1022                 bprm->loader = loader;
1023                 retval = prepare_binprm(bprm);
1024                 if (retval<0)
1025                         return retval;
1026                 /* should call search_binary_handler recursively here,
1027                    but it does not matter */
1028             }
1029         }
1030 #endif
1031         retval = security_bprm_check(bprm);
1032         if (retval)
1033                 return retval;
1034
1035         /* kernel module loader fixup */
1036         /* so we don't try to load run modprobe in kernel space. */
1037         set_fs(USER_DS);
1038         for (try=0; try<2; try++) {
1039                 read_lock(&binfmt_lock);
1040                 for (fmt = formats ; fmt ; fmt = fmt->next) {
1041                         int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
1042                         if (!fn)
1043                                 continue;
1044                         if (!try_module_get(fmt->module))
1045                                 continue;
1046                         read_unlock(&binfmt_lock);
1047                         retval = fn(bprm, regs);
1048                         if (retval >= 0) {
1049                                 put_binfmt(fmt);
1050                                 allow_write_access(bprm->file);
1051                                 if (bprm->file)
1052                                         fput(bprm->file);
1053                                 bprm->file = NULL;
1054                                 current->did_exec = 1;
1055                                 return retval;
1056                         }
1057                         read_lock(&binfmt_lock);
1058                         put_binfmt(fmt);
1059                         if (retval != -ENOEXEC || bprm->mm == NULL)
1060                                 break;
1061                         if (!bprm->file) {
1062                                 read_unlock(&binfmt_lock);
1063                                 return retval;
1064                         }
1065                 }
1066                 read_unlock(&binfmt_lock);
1067                 if (retval != -ENOEXEC || bprm->mm == NULL) {
1068                         break;
1069 #ifdef CONFIG_KMOD
1070                 }else{
1071 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
1072                         if (printable(bprm->buf[0]) &&
1073                             printable(bprm->buf[1]) &&
1074                             printable(bprm->buf[2]) &&
1075                             printable(bprm->buf[3]))
1076                                 break; /* -ENOEXEC */
1077                         request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
1078 #endif
1079                 }
1080         }
1081         return retval;
1082 }
1083
1084 EXPORT_SYMBOL(search_binary_handler);
1085
1086 /*
1087  * sys_execve() executes a new program.
1088  */
1089 int do_execve(char * filename,
1090         char __user *__user *argv,
1091         char __user *__user *envp,
1092         struct pt_regs * regs)
1093 {
1094         struct linux_binprm bprm;
1095         struct file *file;
1096         int retval;
1097         int i;
1098
1099         file = open_exec(filename);
1100
1101         retval = PTR_ERR(file);
1102         if (IS_ERR(file))
1103                 return retval;
1104
1105         sched_balance_exec();
1106
1107         bprm.p = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1108         memset(bprm.page, 0, MAX_ARG_PAGES*sizeof(bprm.page[0]));
1109
1110         bprm.file = file;
1111         bprm.filename = filename;
1112         bprm.interp = filename;
1113         bprm.interp_flags = 0;
1114         bprm.interp_data = 0;
1115         bprm.sh_bang = 0;
1116         bprm.loader = 0;
1117         bprm.exec = 0;
1118         bprm.security = NULL;
1119         bprm.mm = mm_alloc();
1120         retval = -ENOMEM;
1121         if (!bprm.mm)
1122                 goto out_file;
1123
1124         retval = init_new_context(current, bprm.mm);
1125         if (retval < 0)
1126                 goto out_mm;
1127
1128         bprm.argc = count(argv, bprm.p / sizeof(void *));
1129         if ((retval = bprm.argc) < 0)
1130                 goto out_mm;
1131
1132         bprm.envc = count(envp, bprm.p / sizeof(void *));
1133         if ((retval = bprm.envc) < 0)
1134                 goto out_mm;
1135
1136         retval = security_bprm_alloc(&bprm);
1137         if (retval)
1138                 goto out;
1139
1140         retval = prepare_binprm(&bprm);
1141         if (retval < 0)
1142                 goto out;
1143
1144         retval = copy_strings_kernel(1, &bprm.filename, &bprm);
1145         if (retval < 0)
1146                 goto out;
1147
1148         bprm.exec = bprm.p;
1149         retval = copy_strings(bprm.envc, envp, &bprm);
1150         if (retval < 0)
1151                 goto out;
1152
1153         retval = copy_strings(bprm.argc, argv, &bprm);
1154         if (retval < 0)
1155                 goto out;
1156
1157         retval = search_binary_handler(&bprm,regs);
1158         if (retval >= 0) {
1159                 free_arg_pages(&bprm);
1160
1161                 /* execve success */
1162                 security_bprm_free(&bprm);
1163                 return retval;
1164         }
1165
1166 out:
1167         /* Something went wrong, return the inode and free the argument pages*/
1168         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
1169                 struct page * page = bprm.page[i];
1170                 if (page)
1171                         __free_page(page);
1172         }
1173
1174         if (bprm.security)
1175                 security_bprm_free(&bprm);
1176
1177 out_mm:
1178         if (bprm.mm)
1179                 mmdrop(bprm.mm);
1180
1181 out_file:
1182         if (bprm.file) {
1183                 allow_write_access(bprm.file);
1184                 fput(bprm.file);
1185         }
1186         return retval;
1187 }
1188
1189 EXPORT_SYMBOL(do_execve);
1190
1191 int set_binfmt(struct linux_binfmt *new)
1192 {
1193         struct linux_binfmt *old = current->binfmt;
1194
1195         if (new) {
1196                 if (!try_module_get(new->module))
1197                         return -1;
1198         }
1199         current->binfmt = new;
1200         if (old)
1201                 module_put(old->module);
1202         return 0;
1203 }
1204
1205 EXPORT_SYMBOL(set_binfmt);
1206
1207 #define CORENAME_MAX_SIZE 64
1208
1209 /* format_corename will inspect the pattern parameter, and output a
1210  * name into corename, which must have space for at least
1211  * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
1212  */
1213 void format_corename(char *corename, const char *pattern, long signr)
1214 {
1215         const char *pat_ptr = pattern;
1216         char *out_ptr = corename;
1217         char *const out_end = corename + CORENAME_MAX_SIZE;
1218         int rc;
1219         int pid_in_pattern = 0;
1220
1221         /* Repeat as long as we have more pattern to process and more output
1222            space */
1223         while (*pat_ptr) {
1224                 if (*pat_ptr != '%') {
1225                         if (out_ptr == out_end)
1226                                 goto out;
1227                         *out_ptr++ = *pat_ptr++;
1228                 } else {
1229                         switch (*++pat_ptr) {
1230                         case 0:
1231                                 goto out;
1232                         /* Double percent, output one percent */
1233                         case '%':
1234                                 if (out_ptr == out_end)
1235                                         goto out;
1236                                 *out_ptr++ = '%';
1237                                 break;
1238                         /* pid */
1239                         case 'p':
1240                                 pid_in_pattern = 1;
1241                                 rc = snprintf(out_ptr, out_end - out_ptr,
1242                                               "%d", current->tgid);
1243                                 if (rc > out_end - out_ptr)
1244                                         goto out;
1245                                 out_ptr += rc;
1246                                 break;
1247                         /* uid */
1248                         case 'u':
1249                                 rc = snprintf(out_ptr, out_end - out_ptr,
1250                                               "%d", current->uid);
1251                                 if (rc > out_end - out_ptr)
1252                                         goto out;
1253                                 out_ptr += rc;
1254                                 break;
1255                         /* gid */
1256                         case 'g':
1257                                 rc = snprintf(out_ptr, out_end - out_ptr,
1258                                               "%d", current->gid);
1259                                 if (rc > out_end - out_ptr)
1260                                         goto out;
1261                                 out_ptr += rc;
1262                                 break;
1263                         /* signal that caused the coredump */
1264                         case 's':
1265                                 rc = snprintf(out_ptr, out_end - out_ptr,
1266                                               "%ld", signr);
1267                                 if (rc > out_end - out_ptr)
1268                                         goto out;
1269                                 out_ptr += rc;
1270                                 break;
1271                         /* UNIX time of coredump */
1272                         case 't': {
1273                                 struct timeval tv;
1274                                 do_gettimeofday(&tv);
1275                                 rc = snprintf(out_ptr, out_end - out_ptr,
1276                                               "%lu", tv.tv_sec);
1277                                 if (rc > out_end - out_ptr)
1278                                         goto out;
1279                                 out_ptr += rc;
1280                                 break;
1281                         }
1282                         /* hostname */
1283                         case 'h':
1284                                 down_read(&uts_sem);
1285                                 rc = snprintf(out_ptr, out_end - out_ptr,
1286                                               "%s", system_utsname.nodename);
1287                                 up_read(&uts_sem);
1288                                 if (rc > out_end - out_ptr)
1289                                         goto out;
1290                                 out_ptr += rc;
1291                                 break;
1292                         /* executable */
1293                         case 'e':
1294                                 rc = snprintf(out_ptr, out_end - out_ptr,
1295                                               "%s", current->comm);
1296                                 if (rc > out_end - out_ptr)
1297                                         goto out;
1298                                 out_ptr += rc;
1299                                 break;
1300                         default:
1301                                 break;
1302                         }
1303                         ++pat_ptr;
1304                 }
1305         }
1306         /* Backward compatibility with core_uses_pid:
1307          *
1308          * If core_pattern does not include a %p (as is the default)
1309          * and core_uses_pid is set, then .%pid will be appended to
1310          * the filename */
1311         if (!pid_in_pattern
1312             && (core_uses_pid || atomic_read(&current->mm->mm_users) != 1)) {
1313                 rc = snprintf(out_ptr, out_end - out_ptr,
1314                               ".%d", current->tgid);
1315                 if (rc > out_end - out_ptr)
1316                         goto out;
1317                 out_ptr += rc;
1318         }
1319       out:
1320         *out_ptr = 0;
1321 }
1322
1323 static void zap_threads (struct mm_struct *mm)
1324 {
1325         struct task_struct *g, *p;
1326         struct task_struct *tsk = current;
1327         struct completion *vfork_done = tsk->vfork_done;
1328
1329         /*
1330          * Make sure nobody is waiting for us to release the VM,
1331          * otherwise we can deadlock when we wait on each other
1332          */
1333         if (vfork_done) {
1334                 tsk->vfork_done = NULL;
1335                 complete(vfork_done);
1336         }
1337
1338         read_lock(&tasklist_lock);
1339         do_each_thread(g,p)
1340                 if (mm == p->mm && p != tsk) {
1341                         force_sig_specific(SIGKILL, p);
1342                         mm->core_waiters++;
1343                 }
1344         while_each_thread(g,p);
1345
1346         read_unlock(&tasklist_lock);
1347 }
1348
1349 static void coredump_wait(struct mm_struct *mm)
1350 {
1351         DECLARE_COMPLETION(startup_done);
1352
1353         mm->core_waiters++; /* let other threads block */
1354         mm->core_startup_done = &startup_done;
1355
1356         /* give other threads a chance to run: */
1357         yield();
1358
1359         zap_threads(mm);
1360         if (--mm->core_waiters) {
1361                 up_write(&mm->mmap_sem);
1362                 wait_for_completion(&startup_done);
1363         } else
1364                 up_write(&mm->mmap_sem);
1365         BUG_ON(mm->core_waiters);
1366 }
1367
1368 int do_coredump(long signr, int exit_code, struct pt_regs * regs)
1369 {
1370         char corename[CORENAME_MAX_SIZE + 1];
1371         struct mm_struct *mm = current->mm;
1372         struct linux_binfmt * binfmt;
1373         struct inode * inode;
1374         struct file * file;
1375         int retval = 0;
1376
1377         lock_kernel();
1378         binfmt = current->binfmt;
1379         if (!binfmt || !binfmt->core_dump)
1380                 goto fail;
1381         down_write(&mm->mmap_sem);
1382         if (!mm->dumpable) {
1383                 up_write(&mm->mmap_sem);
1384                 goto fail;
1385         }
1386         mm->dumpable = 0;
1387         init_completion(&mm->core_done);
1388         current->signal->group_exit = 1;
1389         current->signal->group_exit_code = exit_code;
1390         coredump_wait(mm);
1391
1392         if (current->rlim[RLIMIT_CORE].rlim_cur < binfmt->min_coredump)
1393                 goto fail_unlock;
1394
1395         format_corename(corename, core_pattern, signr);
1396         file = filp_open(corename, O_CREAT | 2 | O_NOFOLLOW | O_LARGEFILE, 0600);
1397         if (IS_ERR(file))
1398                 goto fail_unlock;
1399         inode = file->f_dentry->d_inode;
1400         if (inode->i_nlink > 1)
1401                 goto close_fail;        /* multiple links - don't dump */
1402         if (d_unhashed(file->f_dentry))
1403                 goto close_fail;
1404
1405         if (!S_ISREG(inode->i_mode))
1406                 goto close_fail;
1407         if (!file->f_op)
1408                 goto close_fail;
1409         if (!file->f_op->write)
1410                 goto close_fail;
1411         if (do_truncate(file->f_dentry, 0) != 0)
1412                 goto close_fail;
1413
1414         retval = binfmt->core_dump(signr, regs, file);
1415
1416         current->signal->group_exit_code |= 0x80;
1417 close_fail:
1418         filp_close(file, NULL);
1419 fail_unlock:
1420         complete_all(&mm->core_done);
1421 fail:
1422         unlock_kernel();
1423         return retval;
1424 }