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