linux-2_6_7
[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         lru_cache_add_active(page);
325         set_pte(pte, pte_mkdirty(pte_mkwrite(mk_pte(
326                                         page, vma->vm_page_prot))));
327         page_add_anon_rmap(page, vma, address);
328         pte_unmap(pte);
329         spin_unlock(&mm->page_table_lock);
330
331         /* no need for flush_tlb */
332         return;
333 out:
334         spin_unlock(&mm->page_table_lock);
335 out_sig:
336         __free_page(page);
337         force_sig(SIGKILL, current);
338 }
339
340 int setup_arg_pages(struct linux_binprm *bprm, int executable_stack)
341 {
342         unsigned long stack_base;
343         struct vm_area_struct *mpnt;
344         struct mm_struct *mm = current->mm;
345         int i;
346         long arg_size;
347
348 #ifdef CONFIG_STACK_GROWSUP
349         /* Move the argument and environment strings to the bottom of the
350          * stack space.
351          */
352         int offset, j;
353         char *to, *from;
354
355         /* Start by shifting all the pages down */
356         i = 0;
357         for (j = 0; j < MAX_ARG_PAGES; j++) {
358                 struct page *page = bprm->page[j];
359                 if (!page)
360                         continue;
361                 bprm->page[i++] = page;
362         }
363
364         /* Now move them within their pages */
365         offset = bprm->p % PAGE_SIZE;
366         to = kmap(bprm->page[0]);
367         for (j = 1; j < i; j++) {
368                 memmove(to, to + offset, PAGE_SIZE - offset);
369                 from = kmap(bprm->page[j]);
370                 memcpy(to + PAGE_SIZE - offset, from, offset);
371                 kunmap(bprm->page[j - 1]);
372                 to = from;
373         }
374         memmove(to, to + offset, PAGE_SIZE - offset);
375         kunmap(bprm->page[j - 1]);
376
377         /* Adjust bprm->p to point to the end of the strings. */
378         bprm->p = PAGE_SIZE * i - offset;
379
380         /* Limit stack size to 1GB */
381         stack_base = current->rlim[RLIMIT_STACK].rlim_max;
382         if (stack_base > (1 << 30))
383                 stack_base = 1 << 30;
384         stack_base = PAGE_ALIGN(STACK_TOP - stack_base);
385
386         mm->arg_start = stack_base;
387         arg_size = i << PAGE_SHIFT;
388
389         /* zero pages that were copied above */
390         while (i < MAX_ARG_PAGES)
391                 bprm->page[i++] = NULL;
392 #else
393         stack_base = STACK_TOP - MAX_ARG_PAGES * PAGE_SIZE;
394         mm->arg_start = bprm->p + stack_base;
395         arg_size = STACK_TOP - (PAGE_MASK & (unsigned long) mm->arg_start);
396 #endif
397
398         bprm->p += stack_base;
399         if (bprm->loader)
400                 bprm->loader += stack_base;
401         bprm->exec += stack_base;
402
403         mpnt = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
404         if (!mpnt)
405                 return -ENOMEM;
406
407         if (security_vm_enough_memory(arg_size >> PAGE_SHIFT)) {
408                 kmem_cache_free(vm_area_cachep, mpnt);
409                 return -ENOMEM;
410         }
411
412         memset(mpnt, 0, sizeof(*mpnt));
413
414         down_write(&mm->mmap_sem);
415         {
416                 mpnt->vm_mm = mm;
417 #ifdef CONFIG_STACK_GROWSUP
418                 mpnt->vm_start = stack_base;
419                 mpnt->vm_end = PAGE_MASK &
420                         (PAGE_SIZE - 1 + (unsigned long) bprm->p);
421 #else
422                 mpnt->vm_start = PAGE_MASK & (unsigned long) bprm->p;
423                 mpnt->vm_end = STACK_TOP;
424 #endif
425                 /* Adjust stack execute permissions; explicitly enable
426                  * for EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X
427                  * and leave alone (arch default) otherwise. */
428                 if (unlikely(executable_stack == EXSTACK_ENABLE_X))
429                         mpnt->vm_flags = VM_STACK_FLAGS |  VM_EXEC;
430                 else if (executable_stack == EXSTACK_DISABLE_X)
431                         mpnt->vm_flags = VM_STACK_FLAGS & ~VM_EXEC;
432                 else
433                         mpnt->vm_flags = VM_STACK_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 int flush_old_exec(struct linux_binprm * bprm)
790 {
791         char * name;
792         int i, ch, retval;
793         struct files_struct *files;
794
795         /*
796          * Make sure we have a private signal table and that
797          * we are unassociated from the previous thread group.
798          */
799         retval = de_thread(current);
800         if (retval)
801                 goto out;
802
803         /*
804          * Make sure we have private file handles. Ask the
805          * fork helper to do the work for us and the exit
806          * helper to do the cleanup of the old one.
807          */
808         files = current->files;         /* refcounted so safe to hold */
809         retval = unshare_files();
810         if (retval)
811                 goto out;
812         /*
813          * Release all of the old mmap stuff
814          */
815         retval = exec_mmap(bprm->mm);
816         if (retval)
817                 goto mmap_failed;
818
819         bprm->mm = NULL;                /* We're using it now */
820
821         /* This is the point of no return */
822         steal_locks(files);
823         put_files_struct(files);
824
825         current->sas_ss_sp = current->sas_ss_size = 0;
826
827         if (current->euid == current->uid && current->egid == current->gid)
828                 current->mm->dumpable = 1;
829         name = bprm->filename;
830         for (i=0; (ch = *(name++)) != '\0';) {
831                 if (ch == '/')
832                         i = 0;
833                 else
834                         if (i < 15)
835                                 current->comm[i++] = ch;
836         }
837         current->comm[i] = '\0';
838
839         flush_thread();
840
841         if (bprm->e_uid != current->euid || bprm->e_gid != current->egid || 
842             permission(bprm->file->f_dentry->d_inode,MAY_READ, NULL))
843                 current->mm->dumpable = 0;
844
845         /* An exec changes our domain. We are no longer part of the thread
846            group */
847
848         current->self_exec_id++;
849                         
850         flush_signal_handlers(current, 0);
851         flush_old_files(current->files);
852
853         return 0;
854
855 mmap_failed:
856         put_files_struct(current->files);
857         current->files = files;
858 out:
859         return retval;
860 }
861
862 EXPORT_SYMBOL(flush_old_exec);
863
864 /* 
865  * Fill the binprm structure from the inode. 
866  * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
867  */
868 int prepare_binprm(struct linux_binprm *bprm)
869 {
870         int mode;
871         struct inode * inode = bprm->file->f_dentry->d_inode;
872         int retval;
873
874         mode = inode->i_mode;
875         /*
876          * Check execute perms again - if the caller has CAP_DAC_OVERRIDE,
877          * vfs_permission lets a non-executable through
878          */
879         if (!(mode & 0111))     /* with at least _one_ execute bit set */
880                 return -EACCES;
881         if (bprm->file->f_op == NULL)
882                 return -EACCES;
883
884         bprm->e_uid = current->euid;
885         bprm->e_gid = current->egid;
886
887         if(!(bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)) {
888                 /* Set-uid? */
889                 if (mode & S_ISUID)
890                         bprm->e_uid = inode->i_uid;
891
892                 /* Set-gid? */
893                 /*
894                  * If setgid is set but no group execute bit then this
895                  * is a candidate for mandatory locking, not a setgid
896                  * executable.
897                  */
898                 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
899                         bprm->e_gid = inode->i_gid;
900         }
901
902         /* fill in binprm security blob */
903         retval = security_bprm_set(bprm);
904         if (retval)
905                 return retval;
906
907         memset(bprm->buf,0,BINPRM_BUF_SIZE);
908         return kernel_read(bprm->file,0,bprm->buf,BINPRM_BUF_SIZE);
909 }
910
911 EXPORT_SYMBOL(prepare_binprm);
912
913 static inline int unsafe_exec(struct task_struct *p)
914 {
915         int unsafe = 0;
916         if (p->ptrace & PT_PTRACED) {
917                 if (p->ptrace & PT_PTRACE_CAP)
918                         unsafe |= LSM_UNSAFE_PTRACE_CAP;
919                 else
920                         unsafe |= LSM_UNSAFE_PTRACE;
921         }
922         if (atomic_read(&p->fs->count) > 1 ||
923             atomic_read(&p->files->count) > 1 ||
924             atomic_read(&p->sighand->count) > 1)
925                 unsafe |= LSM_UNSAFE_SHARE;
926
927         return unsafe;
928 }
929
930 void compute_creds(struct linux_binprm *bprm)
931 {
932         int unsafe;
933         task_lock(current);
934         unsafe = unsafe_exec(current);
935         security_bprm_apply_creds(bprm, unsafe);
936         task_unlock(current);
937 }
938
939 EXPORT_SYMBOL(compute_creds);
940
941 void remove_arg_zero(struct linux_binprm *bprm)
942 {
943         if (bprm->argc) {
944                 unsigned long offset;
945                 char * kaddr;
946                 struct page *page;
947
948                 offset = bprm->p % PAGE_SIZE;
949                 goto inside;
950
951                 while (bprm->p++, *(kaddr+offset++)) {
952                         if (offset != PAGE_SIZE)
953                                 continue;
954                         offset = 0;
955                         kunmap_atomic(kaddr, KM_USER0);
956 inside:
957                         page = bprm->page[bprm->p/PAGE_SIZE];
958                         kaddr = kmap_atomic(page, KM_USER0);
959                 }
960                 kunmap_atomic(kaddr, KM_USER0);
961                 bprm->argc--;
962         }
963 }
964
965 EXPORT_SYMBOL(remove_arg_zero);
966
967 /*
968  * cycle the list of binary formats handler, until one recognizes the image
969  */
970 int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs)
971 {
972         int try,retval=0;
973         struct linux_binfmt *fmt;
974 #ifdef __alpha__
975         /* handle /sbin/loader.. */
976         {
977             struct exec * eh = (struct exec *) bprm->buf;
978
979             if (!bprm->loader && eh->fh.f_magic == 0x183 &&
980                 (eh->fh.f_flags & 0x3000) == 0x3000)
981             {
982                 struct file * file;
983                 unsigned long loader;
984
985                 allow_write_access(bprm->file);
986                 fput(bprm->file);
987                 bprm->file = NULL;
988
989                 loader = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
990
991                 file = open_exec("/sbin/loader");
992                 retval = PTR_ERR(file);
993                 if (IS_ERR(file))
994                         return retval;
995
996                 /* Remember if the application is TASO.  */
997                 bprm->sh_bang = eh->ah.entry < 0x100000000UL;
998
999                 bprm->file = file;
1000                 bprm->loader = loader;
1001                 retval = prepare_binprm(bprm);
1002                 if (retval<0)
1003                         return retval;
1004                 /* should call search_binary_handler recursively here,
1005                    but it does not matter */
1006             }
1007         }
1008 #endif
1009         retval = security_bprm_check(bprm);
1010         if (retval)
1011                 return retval;
1012
1013         /* kernel module loader fixup */
1014         /* so we don't try to load run modprobe in kernel space. */
1015         set_fs(USER_DS);
1016         for (try=0; try<2; try++) {
1017                 read_lock(&binfmt_lock);
1018                 for (fmt = formats ; fmt ; fmt = fmt->next) {
1019                         int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
1020                         if (!fn)
1021                                 continue;
1022                         if (!try_module_get(fmt->module))
1023                                 continue;
1024                         read_unlock(&binfmt_lock);
1025                         retval = fn(bprm, regs);
1026                         if (retval >= 0) {
1027                                 put_binfmt(fmt);
1028                                 allow_write_access(bprm->file);
1029                                 if (bprm->file)
1030                                         fput(bprm->file);
1031                                 bprm->file = NULL;
1032                                 current->did_exec = 1;
1033                                 return retval;
1034                         }
1035                         read_lock(&binfmt_lock);
1036                         put_binfmt(fmt);
1037                         if (retval != -ENOEXEC || bprm->mm == NULL)
1038                                 break;
1039                         if (!bprm->file) {
1040                                 read_unlock(&binfmt_lock);
1041                                 return retval;
1042                         }
1043                 }
1044                 read_unlock(&binfmt_lock);
1045                 if (retval != -ENOEXEC || bprm->mm == NULL) {
1046                         break;
1047 #ifdef CONFIG_KMOD
1048                 }else{
1049 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
1050                         if (printable(bprm->buf[0]) &&
1051                             printable(bprm->buf[1]) &&
1052                             printable(bprm->buf[2]) &&
1053                             printable(bprm->buf[3]))
1054                                 break; /* -ENOEXEC */
1055                         request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
1056 #endif
1057                 }
1058         }
1059         return retval;
1060 }
1061
1062 EXPORT_SYMBOL(search_binary_handler);
1063
1064 /*
1065  * sys_execve() executes a new program.
1066  */
1067 int do_execve(char * filename,
1068         char __user *__user *argv,
1069         char __user *__user *envp,
1070         struct pt_regs * regs)
1071 {
1072         struct linux_binprm bprm;
1073         struct file *file;
1074         int retval;
1075         int i;
1076
1077         file = open_exec(filename);
1078
1079         retval = PTR_ERR(file);
1080         if (IS_ERR(file))
1081                 return retval;
1082
1083         sched_balance_exec();
1084
1085         bprm.p = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
1086         memset(bprm.page, 0, MAX_ARG_PAGES*sizeof(bprm.page[0]));
1087
1088         bprm.file = file;
1089         bprm.filename = filename;
1090         bprm.interp = filename;
1091         bprm.sh_bang = 0;
1092         bprm.loader = 0;
1093         bprm.exec = 0;
1094         bprm.security = NULL;
1095         bprm.mm = mm_alloc();
1096         retval = -ENOMEM;
1097         if (!bprm.mm)
1098                 goto out_file;
1099
1100         retval = init_new_context(current, bprm.mm);
1101         if (retval < 0)
1102                 goto out_mm;
1103
1104         bprm.argc = count(argv, bprm.p / sizeof(void *));
1105         if ((retval = bprm.argc) < 0)
1106                 goto out_mm;
1107
1108         bprm.envc = count(envp, bprm.p / sizeof(void *));
1109         if ((retval = bprm.envc) < 0)
1110                 goto out_mm;
1111
1112         retval = security_bprm_alloc(&bprm);
1113         if (retval)
1114                 goto out;
1115
1116         retval = prepare_binprm(&bprm);
1117         if (retval < 0)
1118                 goto out;
1119
1120         retval = copy_strings_kernel(1, &bprm.filename, &bprm);
1121         if (retval < 0)
1122                 goto out;
1123
1124         bprm.exec = bprm.p;
1125         retval = copy_strings(bprm.envc, envp, &bprm);
1126         if (retval < 0)
1127                 goto out;
1128
1129         retval = copy_strings(bprm.argc, argv, &bprm);
1130         if (retval < 0)
1131                 goto out;
1132
1133         retval = search_binary_handler(&bprm,regs);
1134         if (retval >= 0) {
1135                 free_arg_pages(&bprm);
1136
1137                 /* execve success */
1138                 security_bprm_free(&bprm);
1139                 return retval;
1140         }
1141
1142 out:
1143         /* Something went wrong, return the inode and free the argument pages*/
1144         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
1145                 struct page * page = bprm.page[i];
1146                 if (page)
1147                         __free_page(page);
1148         }
1149
1150         if (bprm.security)
1151                 security_bprm_free(&bprm);
1152
1153 out_mm:
1154         if (bprm.mm)
1155                 mmdrop(bprm.mm);
1156
1157 out_file:
1158         if (bprm.file) {
1159                 allow_write_access(bprm.file);
1160                 fput(bprm.file);
1161         }
1162         return retval;
1163 }
1164
1165 EXPORT_SYMBOL(do_execve);
1166
1167 int set_binfmt(struct linux_binfmt *new)
1168 {
1169         struct linux_binfmt *old = current->binfmt;
1170
1171         if (new) {
1172                 if (!try_module_get(new->module))
1173                         return -1;
1174         }
1175         current->binfmt = new;
1176         if (old)
1177                 module_put(old->module);
1178         return 0;
1179 }
1180
1181 EXPORT_SYMBOL(set_binfmt);
1182
1183 #define CORENAME_MAX_SIZE 64
1184
1185 /* format_corename will inspect the pattern parameter, and output a
1186  * name into corename, which must have space for at least
1187  * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
1188  */
1189 void format_corename(char *corename, const char *pattern, long signr)
1190 {
1191         const char *pat_ptr = pattern;
1192         char *out_ptr = corename;
1193         char *const out_end = corename + CORENAME_MAX_SIZE;
1194         int rc;
1195         int pid_in_pattern = 0;
1196
1197         /* Repeat as long as we have more pattern to process and more output
1198            space */
1199         while (*pat_ptr) {
1200                 if (*pat_ptr != '%') {
1201                         if (out_ptr == out_end)
1202                                 goto out;
1203                         *out_ptr++ = *pat_ptr++;
1204                 } else {
1205                         switch (*++pat_ptr) {
1206                         case 0:
1207                                 goto out;
1208                         /* Double percent, output one percent */
1209                         case '%':
1210                                 if (out_ptr == out_end)
1211                                         goto out;
1212                                 *out_ptr++ = '%';
1213                                 break;
1214                         /* pid */
1215                         case 'p':
1216                                 pid_in_pattern = 1;
1217                                 rc = snprintf(out_ptr, out_end - out_ptr,
1218                                               "%d", current->tgid);
1219                                 if (rc > out_end - out_ptr)
1220                                         goto out;
1221                                 out_ptr += rc;
1222                                 break;
1223                         /* uid */
1224                         case 'u':
1225                                 rc = snprintf(out_ptr, out_end - out_ptr,
1226                                               "%d", current->uid);
1227                                 if (rc > out_end - out_ptr)
1228                                         goto out;
1229                                 out_ptr += rc;
1230                                 break;
1231                         /* gid */
1232                         case 'g':
1233                                 rc = snprintf(out_ptr, out_end - out_ptr,
1234                                               "%d", current->gid);
1235                                 if (rc > out_end - out_ptr)
1236                                         goto out;
1237                                 out_ptr += rc;
1238                                 break;
1239                         /* signal that caused the coredump */
1240                         case 's':
1241                                 rc = snprintf(out_ptr, out_end - out_ptr,
1242                                               "%ld", signr);
1243                                 if (rc > out_end - out_ptr)
1244                                         goto out;
1245                                 out_ptr += rc;
1246                                 break;
1247                         /* UNIX time of coredump */
1248                         case 't': {
1249                                 struct timeval tv;
1250                                 do_gettimeofday(&tv);
1251                                 rc = snprintf(out_ptr, out_end - out_ptr,
1252                                               "%lu", tv.tv_sec);
1253                                 if (rc > out_end - out_ptr)
1254                                         goto out;
1255                                 out_ptr += rc;
1256                                 break;
1257                         }
1258                         /* hostname */
1259                         case 'h':
1260                                 down_read(&uts_sem);
1261                                 rc = snprintf(out_ptr, out_end - out_ptr,
1262                                               "%s", system_utsname.nodename);
1263                                 up_read(&uts_sem);
1264                                 if (rc > out_end - out_ptr)
1265                                         goto out;
1266                                 out_ptr += rc;
1267                                 break;
1268                         /* executable */
1269                         case 'e':
1270                                 rc = snprintf(out_ptr, out_end - out_ptr,
1271                                               "%s", current->comm);
1272                                 if (rc > out_end - out_ptr)
1273                                         goto out;
1274                                 out_ptr += rc;
1275                                 break;
1276                         default:
1277                                 break;
1278                         }
1279                         ++pat_ptr;
1280                 }
1281         }
1282         /* Backward compatibility with core_uses_pid:
1283          *
1284          * If core_pattern does not include a %p (as is the default)
1285          * and core_uses_pid is set, then .%pid will be appended to
1286          * the filename */
1287         if (!pid_in_pattern
1288             && (core_uses_pid || atomic_read(&current->mm->mm_users) != 1)) {
1289                 rc = snprintf(out_ptr, out_end - out_ptr,
1290                               ".%d", current->tgid);
1291                 if (rc > out_end - out_ptr)
1292                         goto out;
1293                 out_ptr += rc;
1294         }
1295       out:
1296         *out_ptr = 0;
1297 }
1298
1299 static void zap_threads (struct mm_struct *mm)
1300 {
1301         struct task_struct *g, *p;
1302         struct task_struct *tsk = current;
1303         struct completion *vfork_done = tsk->vfork_done;
1304
1305         /*
1306          * Make sure nobody is waiting for us to release the VM,
1307          * otherwise we can deadlock when we wait on each other
1308          */
1309         if (vfork_done) {
1310                 tsk->vfork_done = NULL;
1311                 complete(vfork_done);
1312         }
1313
1314         read_lock(&tasklist_lock);
1315         do_each_thread(g,p)
1316                 if (mm == p->mm && p != tsk) {
1317                         force_sig_specific(SIGKILL, p);
1318                         mm->core_waiters++;
1319                 }
1320         while_each_thread(g,p);
1321
1322         read_unlock(&tasklist_lock);
1323 }
1324
1325 static void coredump_wait(struct mm_struct *mm)
1326 {
1327         DECLARE_COMPLETION(startup_done);
1328
1329         mm->core_waiters++; /* let other threads block */
1330         mm->core_startup_done = &startup_done;
1331
1332         /* give other threads a chance to run: */
1333         yield();
1334
1335         zap_threads(mm);
1336         if (--mm->core_waiters) {
1337                 up_write(&mm->mmap_sem);
1338                 wait_for_completion(&startup_done);
1339         } else
1340                 up_write(&mm->mmap_sem);
1341         BUG_ON(mm->core_waiters);
1342 }
1343
1344 int do_coredump(long signr, int exit_code, struct pt_regs * regs)
1345 {
1346         char corename[CORENAME_MAX_SIZE + 1];
1347         struct mm_struct *mm = current->mm;
1348         struct linux_binfmt * binfmt;
1349         struct inode * inode;
1350         struct file * file;
1351         int retval = 0;
1352
1353         lock_kernel();
1354         binfmt = current->binfmt;
1355         if (!binfmt || !binfmt->core_dump)
1356                 goto fail;
1357         down_write(&mm->mmap_sem);
1358         if (!mm->dumpable) {
1359                 up_write(&mm->mmap_sem);
1360                 goto fail;
1361         }
1362         mm->dumpable = 0;
1363         init_completion(&mm->core_done);
1364         current->signal->group_exit = 1;
1365         current->signal->group_exit_code = exit_code;
1366         coredump_wait(mm);
1367
1368         if (current->rlim[RLIMIT_CORE].rlim_cur < binfmt->min_coredump)
1369                 goto fail_unlock;
1370
1371         format_corename(corename, core_pattern, signr);
1372         file = filp_open(corename, O_CREAT | 2 | O_NOFOLLOW | O_LARGEFILE, 0600);
1373         if (IS_ERR(file))
1374                 goto fail_unlock;
1375         inode = file->f_dentry->d_inode;
1376         if (inode->i_nlink > 1)
1377                 goto close_fail;        /* multiple links - don't dump */
1378         if (d_unhashed(file->f_dentry))
1379                 goto close_fail;
1380
1381         if (!S_ISREG(inode->i_mode))
1382                 goto close_fail;
1383         if (!file->f_op)
1384                 goto close_fail;
1385         if (!file->f_op->write)
1386                 goto close_fail;
1387         if (do_truncate(file->f_dentry, 0) != 0)
1388                 goto close_fail;
1389
1390         retval = binfmt->core_dump(signr, regs, file);
1391
1392         current->signal->group_exit_code |= 0x80;
1393 close_fail:
1394         filp_close(file, NULL);
1395 fail_unlock:
1396         complete_all(&mm->core_done);
1397 fail:
1398         unlock_kernel();
1399         return retval;
1400 }