make oldconfig will rebuild these...
[linux-2.4.21-pre4.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/swap.h>
39 #include <linux/utsname.h>
40 #define __NO_VERSION__
41 #include <linux/module.h>
42
43 #include <asm/uaccess.h>
44 #include <asm/pgalloc.h>
45 #include <asm/mmu_context.h>
46
47 #ifdef CONFIG_KMOD
48 #include <linux/kmod.h>
49 #endif
50
51 int core_uses_pid;
52 char core_pattern[65] = "core";
53 /* The maximal length of core_pattern is also specified in sysctl.c */ 
54
55 static struct linux_binfmt *formats;
56 static rwlock_t binfmt_lock = RW_LOCK_UNLOCKED;
57
58 int register_binfmt(struct linux_binfmt * fmt)
59 {
60         struct linux_binfmt ** tmp = &formats;
61
62         if (!fmt)
63                 return -EINVAL;
64         if (fmt->next)
65                 return -EBUSY;
66         write_lock(&binfmt_lock);
67         while (*tmp) {
68                 if (fmt == *tmp) {
69                         write_unlock(&binfmt_lock);
70                         return -EBUSY;
71                 }
72                 tmp = &(*tmp)->next;
73         }
74         fmt->next = formats;
75         formats = fmt;
76         write_unlock(&binfmt_lock);
77         return 0;       
78 }
79
80 int unregister_binfmt(struct linux_binfmt * fmt)
81 {
82         struct linux_binfmt ** tmp = &formats;
83
84         write_lock(&binfmt_lock);
85         while (*tmp) {
86                 if (fmt == *tmp) {
87                         *tmp = fmt->next;
88                         write_unlock(&binfmt_lock);
89                         return 0;
90                 }
91                 tmp = &(*tmp)->next;
92         }
93         write_unlock(&binfmt_lock);
94         return -EINVAL;
95 }
96
97 static inline void put_binfmt(struct linux_binfmt * fmt)
98 {
99         if (fmt->module)
100                 __MOD_DEC_USE_COUNT(fmt->module);
101 }
102
103 /*
104  * Note that a shared library must be both readable and executable due to
105  * security reasons.
106  *
107  * Also note that we take the address to load from from the file itself.
108  */
109 asmlinkage long sys_uselib(const char * library)
110 {
111         struct file * file;
112         struct nameidata nd;
113         int error;
114
115         error = user_path_walk(library, &nd);
116         if (error)
117                 goto out;
118
119         error = -EINVAL;
120         if (!S_ISREG(nd.dentry->d_inode->i_mode))
121                 goto exit;
122
123         error = permission(nd.dentry->d_inode, MAY_READ | MAY_EXEC);
124         if (error)
125                 goto exit;
126
127         file = dentry_open(nd.dentry, nd.mnt, O_RDONLY);
128         error = PTR_ERR(file);
129         if (IS_ERR(file))
130                 goto out;
131
132         error = -ENOEXEC;
133         if(file->f_op && file->f_op->read) {
134                 struct linux_binfmt * fmt;
135
136                 read_lock(&binfmt_lock);
137                 for (fmt = formats ; fmt ; fmt = fmt->next) {
138                         if (!fmt->load_shlib)
139                                 continue;
140                         if (!try_inc_mod_count(fmt->module))
141                                 continue;
142                         read_unlock(&binfmt_lock);
143                         error = fmt->load_shlib(file);
144                         read_lock(&binfmt_lock);
145                         put_binfmt(fmt);
146                         if (error != -ENOEXEC)
147                                 break;
148                 }
149                 read_unlock(&binfmt_lock);
150         }
151         fput(file);
152 out:
153         return error;
154 exit:
155         path_release(&nd);
156         goto out;
157 }
158
159 /*
160  * count() counts the number of arguments/envelopes
161  */
162 static int count(char ** argv, int max)
163 {
164         int i = 0;
165
166         if (argv != NULL) {
167                 for (;;) {
168                         char * p;
169
170                         if (get_user(p, argv))
171                                 return -EFAULT;
172                         if (!p)
173                                 break;
174                         argv++;
175                         if(++i > max)
176                                 return -E2BIG;
177                 }
178         }
179         return i;
180 }
181
182 /*
183  * 'copy_strings()' copies argument/envelope strings from user
184  * memory to free pages in kernel mem. These are in a format ready
185  * to be put directly into the top of new user memory.
186  */
187 int copy_strings(int argc,char ** argv, struct linux_binprm *bprm) 
188 {
189         struct page *kmapped_page = NULL;
190         char *kaddr = NULL;
191         int ret;
192
193         while (argc-- > 0) {
194                 char *str;
195                 int len;
196                 unsigned long pos;
197
198                 if (get_user(str, argv+argc) ||
199                                 !(len = strnlen_user(str, bprm->p))) {
200                         ret = -EFAULT;
201                         goto out;
202                 }
203
204                 if (bprm->p < len)  {
205                         ret = -E2BIG;
206                         goto out;
207                 }
208
209                 bprm->p -= len;
210                 /* XXX: add architecture specific overflow check here. */ 
211                 pos = bprm->p;
212
213                 while (len > 0) {
214                         int i, new, err;
215                         int offset, bytes_to_copy;
216                         struct page *page;
217
218                         offset = pos % PAGE_SIZE;
219                         i = pos/PAGE_SIZE;
220                         page = bprm->page[i];
221                         new = 0;
222                         if (!page) {
223                                 page = alloc_page(GFP_HIGHUSER);
224                                 bprm->page[i] = page;
225                                 if (!page) {
226                                         ret = -ENOMEM;
227                                         goto out;
228                                 }
229                                 new = 1;
230                         }
231
232                         if (page != kmapped_page) {
233                                 if (kmapped_page)
234                                         kunmap(kmapped_page);
235                                 kmapped_page = page;
236                                 kaddr = kmap(kmapped_page);
237                         }
238                         if (new && offset)
239                                 memset(kaddr, 0, offset);
240                         bytes_to_copy = PAGE_SIZE - offset;
241                         if (bytes_to_copy > len) {
242                                 bytes_to_copy = len;
243                                 if (new)
244                                         memset(kaddr+offset+len, 0,
245                                                 PAGE_SIZE-offset-len);
246                         }
247                         err = copy_from_user(kaddr+offset, str, bytes_to_copy);
248                         if (err) {
249                                 ret = -EFAULT;
250                                 goto out;
251                         }
252
253                         pos += bytes_to_copy;
254                         str += bytes_to_copy;
255                         len -= bytes_to_copy;
256                 }
257         }
258         ret = 0;
259 out:
260         if (kmapped_page)
261                 kunmap(kmapped_page);
262         return ret;
263 }
264
265 /*
266  * Like copy_strings, but get argv and its values from kernel memory.
267  */
268 int copy_strings_kernel(int argc,char ** argv, struct linux_binprm *bprm)
269 {
270         int r;
271         mm_segment_t oldfs = get_fs();
272         set_fs(KERNEL_DS); 
273         r = copy_strings(argc, argv, bprm);
274         set_fs(oldfs);
275         return r; 
276 }
277
278 /*
279  * This routine is used to map in a page into an address space: needed by
280  * execve() for the initial stack and environment pages.
281  *
282  * tsk->mmap_sem is held for writing.
283  */
284 void put_dirty_page(struct task_struct * tsk, struct page *page, unsigned long address)
285 {
286         pgd_t * pgd;
287         pmd_t * pmd;
288         pte_t * pte;
289
290         if (page_count(page) != 1)
291                 printk(KERN_ERR "mem_map disagrees with %p at %08lx\n", page, address);
292         pgd = pgd_offset(tsk->mm, address);
293
294         spin_lock(&tsk->mm->page_table_lock);
295         pmd = pmd_alloc(tsk->mm, pgd, address);
296         if (!pmd)
297                 goto out;
298         pte = pte_alloc(tsk->mm, pmd, address);
299         if (!pte)
300                 goto out;
301         if (!pte_none(*pte))
302                 goto out;
303         lru_cache_add(page);
304         flush_dcache_page(page);
305         flush_page_to_ram(page);
306         set_pte(pte, pte_mkdirty(pte_mkwrite(mk_pte(page, PAGE_COPY))));
307         tsk->mm->rss++;
308         spin_unlock(&tsk->mm->page_table_lock);
309
310         /* no need for flush_tlb */
311         return;
312 out:
313         spin_unlock(&tsk->mm->page_table_lock);
314         __free_page(page);
315         force_sig(SIGKILL, tsk);
316         return;
317 }
318
319 int setup_arg_pages(struct linux_binprm *bprm)
320 {
321         unsigned long stack_base;
322         struct vm_area_struct *mpnt;
323         int i;
324
325         stack_base = STACK_TOP - MAX_ARG_PAGES*PAGE_SIZE;
326
327         bprm->p += stack_base;
328         if (bprm->loader)
329                 bprm->loader += stack_base;
330         bprm->exec += stack_base;
331
332         mpnt = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
333         if (!mpnt) 
334                 return -ENOMEM; 
335         
336         down_write(&current->mm->mmap_sem);
337         {
338                 mpnt->vm_mm = current->mm;
339                 mpnt->vm_start = PAGE_MASK & (unsigned long) bprm->p;
340                 mpnt->vm_end = STACK_TOP;
341                 mpnt->vm_page_prot = PAGE_COPY;
342                 mpnt->vm_flags = VM_STACK_FLAGS;
343                 mpnt->vm_ops = NULL;
344                 mpnt->vm_pgoff = 0;
345                 mpnt->vm_file = NULL;
346                 mpnt->vm_private_data = (void *) 0;
347                 insert_vm_struct(current->mm, mpnt);
348                 current->mm->total_vm = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT;
349         } 
350
351         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
352                 struct page *page = bprm->page[i];
353                 if (page) {
354                         bprm->page[i] = NULL;
355                         put_dirty_page(current,page,stack_base);
356                 }
357                 stack_base += PAGE_SIZE;
358         }
359         up_write(&current->mm->mmap_sem);
360         
361         return 0;
362 }
363
364 struct file *open_exec(const char *name)
365 {
366         struct nameidata nd;
367         struct inode *inode;
368         struct file *file;
369         int err = 0;
370
371         err = path_lookup(name, LOOKUP_FOLLOW|LOOKUP_POSITIVE, &nd);
372         file = ERR_PTR(err);
373         if (!err) {
374                 inode = nd.dentry->d_inode;
375                 file = ERR_PTR(-EACCES);
376                 if (!(nd.mnt->mnt_flags & MNT_NOEXEC) &&
377                     S_ISREG(inode->i_mode)) {
378                         int err = permission(inode, MAY_EXEC);
379                         if (!err && !(inode->i_mode & 0111))
380                                 err = -EACCES;
381                         file = ERR_PTR(err);
382                         if (!err) {
383                                 file = dentry_open(nd.dentry, nd.mnt, O_RDONLY);
384                                 if (!IS_ERR(file)) {
385                                         err = deny_write_access(file);
386                                         if (err) {
387                                                 fput(file);
388                                                 file = ERR_PTR(err);
389                                         }
390                                 }
391 out:
392                                 return file;
393                         }
394                 }
395                 path_release(&nd);
396         }
397         goto out;
398 }
399
400 int kernel_read(struct file *file, unsigned long offset,
401         char * addr, unsigned long count)
402 {
403         mm_segment_t old_fs;
404         loff_t pos = offset;
405         int result = -ENOSYS;
406
407         if (!file->f_op->read)
408                 goto fail;
409         old_fs = get_fs();
410         set_fs(get_ds());
411         result = file->f_op->read(file, addr, count, &pos);
412         set_fs(old_fs);
413 fail:
414         return result;
415 }
416
417 static int exec_mmap(void)
418 {
419         struct mm_struct * mm, * old_mm;
420
421         old_mm = current->mm;
422         if (old_mm && atomic_read(&old_mm->mm_users) == 1) {
423                 mm_release();
424                 exit_mmap(old_mm);
425                 return 0;
426         }
427
428         mm = mm_alloc();
429         if (mm) {
430                 struct mm_struct *active_mm;
431
432                 if (init_new_context(current, mm)) {
433                         mmdrop(mm);
434                         return -ENOMEM;
435                 }
436
437                 /* Add it to the list of mm's */
438                 spin_lock(&mmlist_lock);
439                 list_add(&mm->mmlist, &init_mm.mmlist);
440                 mmlist_nr++;
441                 spin_unlock(&mmlist_lock);
442
443                 task_lock(current);
444                 active_mm = current->active_mm;
445                 current->mm = mm;
446                 current->active_mm = mm;
447                 task_unlock(current);
448                 activate_mm(active_mm, mm);
449                 mm_release();
450                 if (old_mm) {
451                         if (active_mm != old_mm) BUG();
452                         mmput(old_mm);
453                         return 0;
454                 }
455                 mmdrop(active_mm);
456                 return 0;
457         }
458         return -ENOMEM;
459 }
460
461 /*
462  * This function makes sure the current process has its own signal table,
463  * so that flush_signal_handlers can later reset the handlers without
464  * disturbing other processes.  (Other processes might share the signal
465  * table via the CLONE_SIGNAL option to clone().)
466  */
467  
468 static inline int make_private_signals(void)
469 {
470         struct signal_struct * newsig;
471
472         if (atomic_read(&current->sig->count) <= 1)
473                 return 0;
474         newsig = kmem_cache_alloc(sigact_cachep, GFP_KERNEL);
475         if (newsig == NULL)
476                 return -ENOMEM;
477         spin_lock_init(&newsig->siglock);
478         atomic_set(&newsig->count, 1);
479         memcpy(newsig->action, current->sig->action, sizeof(newsig->action));
480         spin_lock_irq(&current->sigmask_lock);
481         current->sig = newsig;
482         spin_unlock_irq(&current->sigmask_lock);
483         return 0;
484 }
485         
486 /*
487  * If make_private_signals() made a copy of the signal table, decrement the
488  * refcount of the original table, and free it if necessary.
489  * We don't do that in make_private_signals() so that we can back off
490  * in flush_old_exec() if an error occurs after calling make_private_signals().
491  */
492
493 static inline void release_old_signals(struct signal_struct * oldsig)
494 {
495         if (current->sig == oldsig)
496                 return;
497         if (atomic_dec_and_test(&oldsig->count))
498                 kmem_cache_free(sigact_cachep, oldsig);
499 }
500
501 /*
502  * These functions flushes out all traces of the currently running executable
503  * so that a new one can be started
504  */
505
506 static inline void flush_old_files(struct files_struct * files)
507 {
508         long j = -1;
509
510         write_lock(&files->file_lock);
511         for (;;) {
512                 unsigned long set, i;
513
514                 j++;
515                 i = j * __NFDBITS;
516                 if (i >= files->max_fds || i >= files->max_fdset)
517                         break;
518                 set = files->close_on_exec->fds_bits[j];
519                 if (!set)
520                         continue;
521                 files->close_on_exec->fds_bits[j] = 0;
522                 write_unlock(&files->file_lock);
523                 for ( ; set ; i++,set >>= 1) {
524                         if (set & 1) {
525                                 sys_close(i);
526                         }
527                 }
528                 write_lock(&files->file_lock);
529
530         }
531         write_unlock(&files->file_lock);
532 }
533
534 /*
535  * An execve() will automatically "de-thread" the process.
536  * Note: we don't have to hold the tasklist_lock to test
537  * whether we migth need to do this. If we're not part of
538  * a thread group, there is no way we can become one
539  * dynamically. And if we are, we only need to protect the
540  * unlink - even if we race with the last other thread exit,
541  * at worst the list_del_init() might end up being a no-op.
542  */
543 static inline void de_thread(struct task_struct *tsk)
544 {
545         if (!list_empty(&tsk->thread_group)) {
546                 write_lock_irq(&tasklist_lock);
547                 list_del_init(&tsk->thread_group);
548                 write_unlock_irq(&tasklist_lock);
549         }
550
551         /* Minor oddity: this might stay the same. */
552         tsk->tgid = tsk->pid;
553 }
554
555 int flush_old_exec(struct linux_binprm * bprm)
556 {
557         char * name;
558         int i, ch, retval;
559         struct signal_struct * oldsig;
560
561         /*
562          * Make sure we have a private signal table
563          */
564         oldsig = current->sig;
565         retval = make_private_signals();
566         if (retval) goto flush_failed;
567
568         /* 
569          * Release all of the old mmap stuff
570          */
571         retval = exec_mmap();
572         if (retval) goto mmap_failed;
573
574         /* This is the point of no return */
575         release_old_signals(oldsig);
576
577         current->sas_ss_sp = current->sas_ss_size = 0;
578
579         if (current->euid == current->uid && current->egid == current->gid)
580                 current->mm->dumpable = 1;
581         name = bprm->filename;
582         for (i=0; (ch = *(name++)) != '\0';) {
583                 if (ch == '/')
584                         i = 0;
585                 else
586                         if (i < 15)
587                                 current->comm[i++] = ch;
588         }
589         current->comm[i] = '\0';
590
591         flush_thread();
592
593         de_thread(current);
594
595         if (bprm->e_uid != current->euid || bprm->e_gid != current->egid || 
596             permission(bprm->file->f_dentry->d_inode,MAY_READ))
597                 current->mm->dumpable = 0;
598
599         /* An exec changes our domain. We are no longer part of the thread
600            group */
601            
602         current->self_exec_id++;
603                         
604         flush_signal_handlers(current);
605         flush_old_files(current->files);
606
607         return 0;
608
609 mmap_failed:
610 flush_failed:
611         spin_lock_irq(&current->sigmask_lock);
612         if (current->sig != oldsig) {
613                 kmem_cache_free(sigact_cachep, current->sig);
614                 current->sig = oldsig;
615         }
616         spin_unlock_irq(&current->sigmask_lock);
617         return retval;
618 }
619
620 /*
621  * We mustn't allow tracing of suid binaries, unless
622  * the tracer has the capability to trace anything..
623  */
624 static inline int must_not_trace_exec(struct task_struct * p)
625 {
626         return (p->ptrace & PT_PTRACED) && !(p->ptrace & PT_PTRACE_CAP);
627 }
628
629 /* 
630  * Fill the binprm structure from the inode. 
631  * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
632  */
633 int prepare_binprm(struct linux_binprm *bprm)
634 {
635         int mode;
636         struct inode * inode = bprm->file->f_dentry->d_inode;
637
638         mode = inode->i_mode;
639         /*
640          * Check execute perms again - if the caller has CAP_DAC_OVERRIDE,
641          * vfs_permission lets a non-executable through
642          */
643         if (!(mode & 0111))     /* with at least _one_ execute bit set */
644                 return -EACCES;
645         if (bprm->file->f_op == NULL)
646                 return -EACCES;
647
648         bprm->e_uid = current->euid;
649         bprm->e_gid = current->egid;
650
651         if(!(bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)) {
652                 /* Set-uid? */
653                 if (mode & S_ISUID)
654                         bprm->e_uid = inode->i_uid;
655
656                 /* Set-gid? */
657                 /*
658                  * If setgid is set but no group execute bit then this
659                  * is a candidate for mandatory locking, not a setgid
660                  * executable.
661                  */
662                 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
663                         bprm->e_gid = inode->i_gid;
664         }
665
666         /* We don't have VFS support for capabilities yet */
667         cap_clear(bprm->cap_inheritable);
668         cap_clear(bprm->cap_permitted);
669         cap_clear(bprm->cap_effective);
670
671         /*  To support inheritance of root-permissions and suid-root
672          *  executables under compatibility mode, we raise all three
673          *  capability sets for the file.
674          *
675          *  If only the real uid is 0, we only raise the inheritable
676          *  and permitted sets of the executable file.
677          */
678
679         if (!issecure(SECURE_NOROOT)) {
680                 if (bprm->e_uid == 0 || current->uid == 0) {
681                         cap_set_full(bprm->cap_inheritable);
682                         cap_set_full(bprm->cap_permitted);
683                 }
684                 if (bprm->e_uid == 0) 
685                         cap_set_full(bprm->cap_effective);
686         }
687
688         memset(bprm->buf,0,BINPRM_BUF_SIZE);
689         return kernel_read(bprm->file,0,bprm->buf,BINPRM_BUF_SIZE);
690 }
691
692 /*
693  * This function is used to produce the new IDs and capabilities
694  * from the old ones and the file's capabilities.
695  *
696  * The formula used for evolving capabilities is:
697  *
698  *       pI' = pI
699  * (***) pP' = (fP & X) | (fI & pI)
700  *       pE' = pP' & fE          [NB. fE is 0 or ~0]
701  *
702  * I=Inheritable, P=Permitted, E=Effective // p=process, f=file
703  * ' indicates post-exec(), and X is the global 'cap_bset'.
704  *
705  */
706
707 void compute_creds(struct linux_binprm *bprm) 
708 {
709         kernel_cap_t new_permitted, working;
710         int do_unlock = 0;
711
712         new_permitted = cap_intersect(bprm->cap_permitted, cap_bset);
713         working = cap_intersect(bprm->cap_inheritable,
714                                 current->cap_inheritable);
715         new_permitted = cap_combine(new_permitted, working);
716
717         if (bprm->e_uid != current->uid || bprm->e_gid != current->gid ||
718             !cap_issubset(new_permitted, current->cap_permitted)) {
719                 current->mm->dumpable = 0;
720                 
721                 lock_kernel();
722                 if (must_not_trace_exec(current)
723                     || atomic_read(&current->fs->count) > 1
724                     || atomic_read(&current->files->count) > 1
725                     || atomic_read(&current->sig->count) > 1) {
726                         if(!capable(CAP_SETUID)) {
727                                 bprm->e_uid = current->uid;
728                                 bprm->e_gid = current->gid;
729                         }
730                         if(!capable(CAP_SETPCAP)) {
731                                 new_permitted = cap_intersect(new_permitted,
732                                                         current->cap_permitted);
733                         }
734                 }
735                 do_unlock = 1;
736         }
737
738
739         /* For init, we want to retain the capabilities set
740          * in the init_task struct. Thus we skip the usual
741          * capability rules */
742         if (current->pid != 1) {
743                 current->cap_permitted = new_permitted;
744                 current->cap_effective =
745                         cap_intersect(new_permitted, bprm->cap_effective);
746         }
747         
748         /* AUD: Audit candidate if current->cap_effective is set */
749
750         current->suid = current->euid = current->fsuid = bprm->e_uid;
751         current->sgid = current->egid = current->fsgid = bprm->e_gid;
752
753         if(do_unlock)
754                 unlock_kernel();
755         current->keep_capabilities = 0;
756 }
757
758
759 void remove_arg_zero(struct linux_binprm *bprm)
760 {
761         if (bprm->argc) {
762                 unsigned long offset;
763                 char * kaddr;
764                 struct page *page;
765
766                 offset = bprm->p % PAGE_SIZE;
767                 goto inside;
768
769                 while (bprm->p++, *(kaddr+offset++)) {
770                         if (offset != PAGE_SIZE)
771                                 continue;
772                         offset = 0;
773                         kunmap(page);
774 inside:
775                         page = bprm->page[bprm->p/PAGE_SIZE];
776                         kaddr = kmap(page);
777                 }
778                 kunmap(page);
779                 bprm->argc--;
780         }
781 }
782
783 /*
784  * cycle the list of binary formats handler, until one recognizes the image
785  */
786 int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs)
787 {
788         int try,retval=0;
789         struct linux_binfmt *fmt;
790 #ifdef __alpha__
791         /* handle /sbin/loader.. */
792         {
793             struct exec * eh = (struct exec *) bprm->buf;
794
795             if (!bprm->loader && eh->fh.f_magic == 0x183 &&
796                 (eh->fh.f_flags & 0x3000) == 0x3000)
797             {
798                 struct file * file;
799                 unsigned long loader;
800
801                 allow_write_access(bprm->file);
802                 fput(bprm->file);
803                 bprm->file = NULL;
804
805                 loader = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
806
807                 file = open_exec("/sbin/loader");
808                 retval = PTR_ERR(file);
809                 if (IS_ERR(file))
810                         return retval;
811
812                 /* Remember if the application is TASO.  */
813                 bprm->sh_bang = eh->ah.entry < 0x100000000;
814
815                 bprm->file = file;
816                 bprm->loader = loader;
817                 retval = prepare_binprm(bprm);
818                 if (retval<0)
819                         return retval;
820                 /* should call search_binary_handler recursively here,
821                    but it does not matter */
822             }
823         }
824 #endif
825         /* kernel module loader fixup */
826         /* so we don't try to load run modprobe in kernel space. */
827         set_fs(USER_DS);
828         for (try=0; try<2; try++) {
829                 read_lock(&binfmt_lock);
830                 for (fmt = formats ; fmt ; fmt = fmt->next) {
831                         int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
832                         if (!fn)
833                                 continue;
834                         if (!try_inc_mod_count(fmt->module))
835                                 continue;
836                         read_unlock(&binfmt_lock);
837                         retval = fn(bprm, regs);
838                         if (retval >= 0) {
839                                 put_binfmt(fmt);
840                                 allow_write_access(bprm->file);
841                                 if (bprm->file)
842                                         fput(bprm->file);
843                                 bprm->file = NULL;
844                                 current->did_exec = 1;
845                                 return retval;
846                         }
847                         read_lock(&binfmt_lock);
848                         put_binfmt(fmt);
849                         if (retval != -ENOEXEC)
850                                 break;
851                         if (!bprm->file) {
852                                 read_unlock(&binfmt_lock);
853                                 return retval;
854                         }
855                 }
856                 read_unlock(&binfmt_lock);
857                 if (retval != -ENOEXEC) {
858                         break;
859 #ifdef CONFIG_KMOD
860                 }else{
861 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
862                         char modname[20];
863                         if (printable(bprm->buf[0]) &&
864                             printable(bprm->buf[1]) &&
865                             printable(bprm->buf[2]) &&
866                             printable(bprm->buf[3]))
867                                 break; /* -ENOEXEC */
868                         sprintf(modname, "binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
869                         request_module(modname);
870 #endif
871                 }
872         }
873         return retval;
874 }
875
876
877 /*
878  * sys_execve() executes a new program.
879  */
880 int do_execve(char * filename, char ** argv, char ** envp, struct pt_regs * regs)
881 {
882         struct linux_binprm bprm;
883         struct file *file;
884         int retval;
885         int i;
886         
887         file = open_exec(filename);
888
889         retval = PTR_ERR(file);
890         if (IS_ERR(file))
891                 return retval;
892
893         bprm.p = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
894         memset(bprm.page, 0, MAX_ARG_PAGES*sizeof(bprm.page[0])); 
895
896         bprm.file = file;
897         bprm.filename = filename;
898         bprm.sh_bang = 0;
899         bprm.loader = 0;
900         bprm.exec = 0;
901         if ((bprm.argc = count(argv, bprm.p / sizeof(void *))) < 0) {
902                 allow_write_access(file);
903                 fput(file);
904                 return bprm.argc;
905         }
906
907         if ((bprm.envc = count(envp, bprm.p / sizeof(void *))) < 0) {
908                 allow_write_access(file);
909                 fput(file);
910                 return bprm.envc;
911         }
912
913         retval = prepare_binprm(&bprm);
914         if (retval < 0) 
915                 goto out; 
916
917         retval = copy_strings_kernel(1, &bprm.filename, &bprm);
918         if (retval < 0) 
919                 goto out; 
920
921         bprm.exec = bprm.p;
922         retval = copy_strings(bprm.envc, envp, &bprm);
923         if (retval < 0) 
924                 goto out; 
925
926         retval = copy_strings(bprm.argc, argv, &bprm);
927         if (retval < 0) 
928                 goto out; 
929
930         retval = search_binary_handler(&bprm,regs);
931         if (retval >= 0)
932                 /* execve success */
933                 return retval;
934
935 out:
936         /* Something went wrong, return the inode and free the argument pages*/
937         allow_write_access(bprm.file);
938         if (bprm.file)
939                 fput(bprm.file);
940
941         for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
942                 struct page * page = bprm.page[i];
943                 if (page)
944                         __free_page(page);
945         }
946
947         return retval;
948 }
949
950 void set_binfmt(struct linux_binfmt *new)
951 {
952         struct linux_binfmt *old = current->binfmt;
953         if (new && new->module)
954                 __MOD_INC_USE_COUNT(new->module);
955         current->binfmt = new;
956         if (old && old->module)
957                 __MOD_DEC_USE_COUNT(old->module);
958 }
959
960 #define CORENAME_MAX_SIZE 64
961
962 /* format_corename will inspect the pattern parameter, and output a
963  * name into corename, which must have space for at least
964  * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
965  */
966 void format_corename(char *corename, const char *pattern, long signr)
967 {
968         const char *pat_ptr = pattern;
969         char *out_ptr = corename;
970         char *const out_end = corename + CORENAME_MAX_SIZE;
971         int rc;
972         int pid_in_pattern = 0;
973
974         /* Repeat as long as we have more pattern to process and more output
975            space */
976         while (*pat_ptr) {
977                 if (*pat_ptr != '%') {
978                         if (out_ptr == out_end)
979                                 goto out;
980                         *out_ptr++ = *pat_ptr++;
981                 } else {
982                         switch (*++pat_ptr) {
983                         case 0:
984                                 goto out;
985                         /* Double percent, output one percent */
986                         case '%':
987                                 if (out_ptr == out_end)
988                                         goto out;
989                                 *out_ptr++ = '%';
990                                 break;
991                         /* pid */
992                         case 'p':
993                                 pid_in_pattern = 1;
994                                 rc = snprintf(out_ptr, out_end - out_ptr,
995                                               "%d", current->pid);
996                                 if (rc > out_end - out_ptr)
997                                         goto out;
998                                 out_ptr += rc;
999                                 break;
1000                         /* uid */
1001                         case 'u':
1002                                 rc = snprintf(out_ptr, out_end - out_ptr,
1003                                               "%d", current->uid);
1004                                 if (rc > out_end - out_ptr)
1005                                         goto out;
1006                                 out_ptr += rc;
1007                                 break;
1008                         /* gid */
1009                         case 'g':
1010                                 rc = snprintf(out_ptr, out_end - out_ptr,
1011                                               "%d", current->gid);
1012                                 if (rc > out_end - out_ptr)
1013                                         goto out;
1014                                 out_ptr += rc;
1015                                 break;
1016                         /* signal that caused the coredump */
1017                         case 's':
1018                                 rc = snprintf(out_ptr, out_end - out_ptr,
1019                                               "%ld", signr);
1020                                 if (rc > out_end - out_ptr)
1021                                         goto out;
1022                                 out_ptr += rc;
1023                                 break;
1024                         /* UNIX time of coredump */
1025                         case 't': {
1026                                 struct timeval tv;
1027                                 do_gettimeofday(&tv);
1028                                 rc = snprintf(out_ptr, out_end - out_ptr,
1029                                               "%ld", tv.tv_sec);
1030                                 if (rc > out_end - out_ptr)
1031                                         goto out;
1032                                 out_ptr += rc;
1033                                 break;
1034                         }
1035                         /* hostname */
1036                         case 'h':
1037                                 down_read(&uts_sem);
1038                                 rc = snprintf(out_ptr, out_end - out_ptr,
1039                                               "%s", system_utsname.nodename);
1040                                 up_read(&uts_sem);
1041                                 if (rc > out_end - out_ptr)
1042                                         goto out;
1043                                 out_ptr += rc;
1044                                 break;
1045                         /* executable */
1046                         case 'e':
1047                                 rc = snprintf(out_ptr, out_end - out_ptr,
1048                                               "%s", current->comm);
1049                                 if (rc > out_end - out_ptr)
1050                                         goto out;
1051                                 out_ptr += rc;
1052                                 break;
1053                         default:
1054                                 break;
1055                         }
1056                         ++pat_ptr;
1057                 }
1058         }
1059         /* Backward compatibility with core_uses_pid:
1060          *
1061          * If core_pattern does not include a %p (as is the default)
1062          * and core_uses_pid is set, then .%pid will be appended to
1063          * the filename */
1064         if (!pid_in_pattern
1065             && (core_uses_pid || atomic_read(&current->mm->mm_users) != 1)) {
1066                 rc = snprintf(out_ptr, out_end - out_ptr,
1067                               ".%d", current->pid);
1068                 if (rc > out_end - out_ptr)
1069                         goto out;
1070                 out_ptr += rc;
1071         }
1072       out:
1073         *out_ptr = 0;
1074 }
1075
1076 int do_coredump(long signr, struct pt_regs * regs)
1077 {
1078         struct linux_binfmt * binfmt;
1079         char corename[CORENAME_MAX_SIZE + 1];
1080         struct file * file;
1081         struct inode * inode;
1082         int retval = 0;
1083
1084         lock_kernel();
1085         binfmt = current->binfmt;
1086         if (!binfmt || !binfmt->core_dump)
1087                 goto fail;
1088         if (!current->mm->dumpable)
1089                 goto fail;
1090         current->mm->dumpable = 0;
1091         if (current->rlim[RLIMIT_CORE].rlim_cur < binfmt->min_coredump)
1092                 goto fail;
1093
1094         format_corename(corename, core_pattern, signr);
1095         file = filp_open(corename, O_CREAT | 2 | O_NOFOLLOW, 0600);
1096         if (IS_ERR(file))
1097                 goto fail;
1098         inode = file->f_dentry->d_inode;
1099         if (inode->i_nlink > 1)
1100                 goto close_fail;        /* multiple links - don't dump */
1101         if (d_unhashed(file->f_dentry))
1102                 goto close_fail;
1103
1104         if (!S_ISREG(inode->i_mode))
1105                 goto close_fail;
1106         if (!file->f_op)
1107                 goto close_fail;
1108         if (!file->f_op->write)
1109                 goto close_fail;
1110         if (do_truncate(file->f_dentry, 0) != 0)
1111                 goto close_fail;
1112
1113         retval = binfmt->core_dump(signr, regs, file);
1114
1115 close_fail:
1116         filp_close(file, NULL);
1117 fail:
1118         unlock_kernel();
1119         return retval;
1120 }