8a5231a4c243038f4631167421b3ab5c89f5eb4f
[linux-2.6.git] / fs / binfmt_elf.c
1 /*
2  * linux/fs/binfmt_elf.c
3  *
4  * These are the functions used to load ELF format executables as used
5  * on SVr4 machines.  Information on the format may be found in the book
6  * "UNIX SYSTEM V RELEASE 4 Programmers Guide: Ansi C and Programming Support
7  * Tools".
8  *
9  * Copyright 1993, 1994: Eric Youngdale (ericy@cais.com).
10  */
11
12 #include <linux/module.h>
13 #include <linux/kernel.h>
14 #include <linux/fs.h>
15 #include <linux/stat.h>
16 #include <linux/time.h>
17 #include <linux/mm.h>
18 #include <linux/mman.h>
19 #include <linux/a.out.h>
20 #include <linux/errno.h>
21 #include <linux/signal.h>
22 #include <linux/binfmts.h>
23 #include <linux/string.h>
24 #include <linux/file.h>
25 #include <linux/fcntl.h>
26 #include <linux/ptrace.h>
27 #include <linux/slab.h>
28 #include <linux/shm.h>
29 #include <linux/personality.h>
30 #include <linux/elfcore.h>
31 #include <linux/init.h>
32 #include <linux/highuid.h>
33 #include <linux/smp.h>
34 #include <linux/smp_lock.h>
35 #include <linux/compiler.h>
36 #include <linux/highmem.h>
37 #include <linux/pagemap.h>
38 #include <linux/security.h>
39 #include <linux/syscalls.h>
40 #include <linux/random.h>
41 #include <linux/elf.h>
42 #include <linux/vs_base.h>
43 #include <linux/vs_memory.h>
44 #include <linux/vs_cvirt.h>
45
46 #include <asm/uaccess.h>
47 #include <asm/param.h>
48 #include <asm/page.h>
49
50
51 static int load_elf_binary(struct linux_binprm *bprm, struct pt_regs *regs);
52 static int load_elf_library(struct file *);
53 static unsigned long elf_map (struct file *, unsigned long, struct elf_phdr *, int, int, unsigned long);
54 extern int dump_fpu (struct pt_regs *, elf_fpregset_t *);
55
56 #ifndef elf_addr_t
57 #define elf_addr_t unsigned long
58 #endif
59
60 /*
61  * If we don't support core dumping, then supply a NULL so we
62  * don't even try.
63  */
64 #if defined(USE_ELF_CORE_DUMP) && defined(CONFIG_ELF_CORE)
65 static int elf_core_dump(long signr, struct pt_regs *regs, struct file *file);
66 #else
67 #define elf_core_dump   NULL
68 #endif
69
70 #if ELF_EXEC_PAGESIZE > PAGE_SIZE
71 #define ELF_MIN_ALIGN   ELF_EXEC_PAGESIZE
72 #else
73 #define ELF_MIN_ALIGN   PAGE_SIZE
74 #endif
75
76 #ifndef ELF_CORE_EFLAGS
77 #define ELF_CORE_EFLAGS 0
78 #endif
79
80 #define ELF_PAGESTART(_v) ((_v) & ~(unsigned long)(ELF_MIN_ALIGN-1))
81 #define ELF_PAGEOFFSET(_v) ((_v) & (ELF_MIN_ALIGN-1))
82 #define ELF_PAGEALIGN(_v) (((_v) + ELF_MIN_ALIGN - 1) & ~(ELF_MIN_ALIGN - 1))
83
84 static struct linux_binfmt elf_format = {
85                 .module         = THIS_MODULE,
86                 .load_binary    = load_elf_binary,
87                 .load_shlib     = load_elf_library,
88                 .core_dump      = elf_core_dump,
89                 .min_coredump   = ELF_EXEC_PAGESIZE
90 };
91
92 #define BAD_ADDR(x) ((unsigned long)(x) >= PAGE_MASK)
93
94 static int set_brk(unsigned long start, unsigned long end)
95 {
96         start = ELF_PAGEALIGN(start);
97         end = ELF_PAGEALIGN(end);
98         if (end > start) {
99                 unsigned long addr;
100                 down_write(&current->mm->mmap_sem);
101                 addr = do_brk(start, end - start);
102                 up_write(&current->mm->mmap_sem);
103                 if (BAD_ADDR(addr))
104                         return addr;
105         }
106         current->mm->start_brk = current->mm->brk = end;
107         return 0;
108 }
109
110 /* We need to explicitly zero any fractional pages
111    after the data section (i.e. bss).  This would
112    contain the junk from the file that should not
113    be in memory
114  */
115 static int padzero(unsigned long elf_bss)
116 {
117         unsigned long nbyte;
118
119         nbyte = ELF_PAGEOFFSET(elf_bss);
120         if (nbyte) {
121                 nbyte = ELF_MIN_ALIGN - nbyte;
122                 if (clear_user((void __user *) elf_bss, nbyte))
123                         return -EFAULT;
124         }
125         return 0;
126 }
127
128 /* Let's use some macros to make this stack manipulation a litle clearer */
129 #ifdef CONFIG_STACK_GROWSUP
130 #define STACK_ADD(sp, items) ((elf_addr_t __user *)(sp) + (items))
131 #define STACK_ROUND(sp, items) \
132         ((15 + (unsigned long) ((sp) + (items))) &~ 15UL)
133 #define STACK_ALLOC(sp, len) ({ \
134         elf_addr_t __user *old_sp = (elf_addr_t __user *)sp; sp += len; \
135         old_sp; })
136 #else
137 #define STACK_ADD(sp, items) ((elf_addr_t __user *)(sp) - (items))
138 #define STACK_ROUND(sp, items) \
139         (((unsigned long) (sp - items)) &~ 15UL)
140 #define STACK_ALLOC(sp, len) ({ sp -= len ; sp; })
141 #endif
142
143 static int
144 create_elf_tables(struct linux_binprm *bprm, struct elfhdr *exec,
145                 int interp_aout, unsigned long load_addr,
146                 unsigned long interp_load_addr)
147 {
148         unsigned long p = bprm->p;
149         int argc = bprm->argc;
150         int envc = bprm->envc;
151         elf_addr_t __user *argv;
152         elf_addr_t __user *envp;
153         elf_addr_t __user *sp;
154         elf_addr_t __user *u_platform;
155         const char *k_platform = ELF_PLATFORM;
156         int items;
157         elf_addr_t *elf_info;
158         int ei_index = 0;
159         struct task_struct *tsk = current;
160
161         /*
162          * If this architecture has a platform capability string, copy it
163          * to userspace.  In some cases (Sparc), this info is impossible
164          * for userspace to get any other way, in others (i386) it is
165          * merely difficult.
166          */
167         u_platform = NULL;
168         if (k_platform) {
169                 size_t len = strlen(k_platform) + 1;
170
171                 /*
172                  * In some cases (e.g. Hyper-Threading), we want to avoid L1
173                  * evictions by the processes running on the same package. One
174                  * thing we can do is to shuffle the initial stack for them.
175                  */
176
177                 p = arch_align_stack(p);
178
179                 u_platform = (elf_addr_t __user *)STACK_ALLOC(p, len);
180                 if (__copy_to_user(u_platform, k_platform, len))
181                         return -EFAULT;
182         }
183
184         /* Create the ELF interpreter info */
185         elf_info = (elf_addr_t *)current->mm->saved_auxv;
186 #define NEW_AUX_ENT(id, val) \
187         do { \
188                 elf_info[ei_index++] = id; \
189                 elf_info[ei_index++] = val; \
190         } while (0)
191
192 #ifdef ARCH_DLINFO
193         /* 
194          * ARCH_DLINFO must come first so PPC can do its special alignment of
195          * AUXV.
196          */
197         ARCH_DLINFO;
198 #endif
199         NEW_AUX_ENT(AT_HWCAP, ELF_HWCAP);
200         NEW_AUX_ENT(AT_PAGESZ, ELF_EXEC_PAGESIZE);
201         NEW_AUX_ENT(AT_CLKTCK, CLOCKS_PER_SEC);
202         NEW_AUX_ENT(AT_PHDR, load_addr + exec->e_phoff);
203         NEW_AUX_ENT(AT_PHENT, sizeof(struct elf_phdr));
204         NEW_AUX_ENT(AT_PHNUM, exec->e_phnum);
205         NEW_AUX_ENT(AT_BASE, interp_load_addr);
206         NEW_AUX_ENT(AT_FLAGS, 0);
207         NEW_AUX_ENT(AT_ENTRY, exec->e_entry);
208         NEW_AUX_ENT(AT_UID, tsk->uid);
209         NEW_AUX_ENT(AT_EUID, tsk->euid);
210         NEW_AUX_ENT(AT_GID, tsk->gid);
211         NEW_AUX_ENT(AT_EGID, tsk->egid);
212         NEW_AUX_ENT(AT_SECURE, security_bprm_secureexec(bprm));
213         if (k_platform) {
214                 NEW_AUX_ENT(AT_PLATFORM,
215                             (elf_addr_t)(unsigned long)u_platform);
216         }
217         if (bprm->interp_flags & BINPRM_FLAGS_EXECFD) {
218                 NEW_AUX_ENT(AT_EXECFD, bprm->interp_data);
219         }
220 #undef NEW_AUX_ENT
221         /* AT_NULL is zero; clear the rest too */
222         memset(&elf_info[ei_index], 0,
223                sizeof current->mm->saved_auxv - ei_index * sizeof elf_info[0]);
224
225         /* And advance past the AT_NULL entry.  */
226         ei_index += 2;
227
228         sp = STACK_ADD(p, ei_index);
229
230         items = (argc + 1) + (envc + 1);
231         if (interp_aout) {
232                 items += 3; /* a.out interpreters require argv & envp too */
233         } else {
234                 items += 1; /* ELF interpreters only put argc on the stack */
235         }
236         bprm->p = STACK_ROUND(sp, items);
237
238         /* Point sp at the lowest address on the stack */
239 #ifdef CONFIG_STACK_GROWSUP
240         sp = (elf_addr_t __user *)bprm->p - items - ei_index;
241         bprm->exec = (unsigned long)sp; /* XXX: PARISC HACK */
242 #else
243         sp = (elf_addr_t __user *)bprm->p;
244 #endif
245
246         /* Now, let's put argc (and argv, envp if appropriate) on the stack */
247         if (__put_user(argc, sp++))
248                 return -EFAULT;
249         if (interp_aout) {
250                 argv = sp + 2;
251                 envp = argv + argc + 1;
252                 __put_user((elf_addr_t)(unsigned long)argv, sp++);
253                 __put_user((elf_addr_t)(unsigned long)envp, sp++);
254         } else {
255                 argv = sp;
256                 envp = argv + argc + 1;
257         }
258
259         /* Populate argv and envp */
260         p = current->mm->arg_end = current->mm->arg_start;
261         while (argc-- > 0) {
262                 size_t len;
263                 __put_user((elf_addr_t)p, argv++);
264                 len = strnlen_user((void __user *)p, PAGE_SIZE*MAX_ARG_PAGES);
265                 if (!len || len > PAGE_SIZE*MAX_ARG_PAGES)
266                         return 0;
267                 p += len;
268         }
269         if (__put_user(0, argv))
270                 return -EFAULT;
271         current->mm->arg_end = current->mm->env_start = p;
272         while (envc-- > 0) {
273                 size_t len;
274                 __put_user((elf_addr_t)p, envp++);
275                 len = strnlen_user((void __user *)p, PAGE_SIZE*MAX_ARG_PAGES);
276                 if (!len || len > PAGE_SIZE*MAX_ARG_PAGES)
277                         return 0;
278                 p += len;
279         }
280         if (__put_user(0, envp))
281                 return -EFAULT;
282         current->mm->env_end = p;
283
284         /* Put the elf_info on the stack in the right place.  */
285         sp = (elf_addr_t __user *)envp + 1;
286         if (copy_to_user(sp, elf_info, ei_index * sizeof(elf_addr_t)))
287                 return -EFAULT;
288         return 0;
289 }
290
291 #ifndef elf_map
292
293 static unsigned long elf_map(struct file *filep, unsigned long addr,
294                 struct elf_phdr *eppnt, int prot, int type,
295                 unsigned long total_size)
296 {
297         unsigned long map_addr;
298         unsigned long size = eppnt->p_filesz + ELF_PAGEOFFSET(eppnt->p_vaddr);
299         unsigned long off = eppnt->p_offset - ELF_PAGEOFFSET(eppnt->p_vaddr);
300
301         addr = ELF_PAGESTART(addr);
302         size = ELF_PAGEALIGN(size);
303
304         /* mmap() will return -EINVAL if given a zero size, but a
305          * segment with zero filesize is perfectly valid */
306         if (!size)
307                 return addr;
308
309         down_write(&current->mm->mmap_sem);
310         /*
311         * total_size is the size of the ELF (interpreter) image.
312         * The _first_ mmap needs to know the full size, otherwise
313         * randomization might put this image into an overlapping
314         * position with the ELF binary image. (since size < total_size)
315         * So we first map the 'big' image - and unmap the remainder at
316         * the end. (which unmap is needed for ELF images with holes.)
317         */
318         if (total_size) {
319                 total_size = ELF_PAGEALIGN(total_size);
320                 map_addr = do_mmap(filep, addr, total_size, prot, type, off);
321                 if (!BAD_ADDR(map_addr))
322                         do_munmap(current->mm, map_addr+size, total_size-size);
323         } else
324                 map_addr = do_mmap(filep, addr, size, prot, type, off);
325
326         up_write(&current->mm->mmap_sem);
327         return(map_addr);
328 }
329
330 #endif /* !elf_map */
331
332 static inline unsigned long total_mapping_size(struct elf_phdr *cmds, int nr)
333 {
334         int i, first_idx = -1, last_idx = -1;
335
336         for (i = 0; i < nr; i++)
337                 if (cmds[i].p_type == PT_LOAD) {
338                         last_idx = i;
339                         if (first_idx == -1)
340                                 first_idx = i;
341                 }
342
343         if (first_idx == -1)
344                 return 0;
345
346         return cmds[last_idx].p_vaddr + cmds[last_idx].p_memsz -
347                                 ELF_PAGESTART(cmds[first_idx].p_vaddr);
348 }
349
350
351 /* This is much more generalized than the library routine read function,
352    so we keep this separate.  Technically the library read function
353    is only provided so that we can read a.out libraries that have
354    an ELF header */
355
356 static unsigned long load_elf_interp(struct elfhdr *interp_elf_ex,
357                 struct file *interpreter, unsigned long *interp_map_addr,
358                 unsigned long no_base)
359 {
360         struct elf_phdr *elf_phdata;
361         struct elf_phdr *eppnt;
362         unsigned long load_addr = 0;
363         int load_addr_set = 0;
364         unsigned long last_bss = 0, elf_bss = 0;
365         unsigned long error = ~0UL;
366         unsigned long total_size;
367         int retval, i, size;
368
369         /* First of all, some simple consistency checks */
370         if (interp_elf_ex->e_type != ET_EXEC &&
371             interp_elf_ex->e_type != ET_DYN)
372                 goto out;
373         if (!elf_check_arch(interp_elf_ex))
374                 goto out;
375         if (!interpreter->f_op || !interpreter->f_op->mmap)
376                 goto out;
377
378         /*
379          * If the size of this structure has changed, then punt, since
380          * we will be doing the wrong thing.
381          */
382         if (interp_elf_ex->e_phentsize != sizeof(struct elf_phdr))
383                 goto out;
384         if (interp_elf_ex->e_phnum < 1 ||
385                 interp_elf_ex->e_phnum > 65536U / sizeof(struct elf_phdr))
386                 goto out;
387
388         /* Now read in all of the header information */
389         size = sizeof(struct elf_phdr) * interp_elf_ex->e_phnum;
390         if (size > ELF_MIN_ALIGN)
391                 goto out;
392         elf_phdata = kmalloc(size, GFP_KERNEL);
393         if (!elf_phdata)
394                 goto out;
395
396         retval = kernel_read(interpreter, interp_elf_ex->e_phoff,
397                              (char *)elf_phdata,size);
398         error = -EIO;
399         if (retval != size) {
400                 if (retval < 0)
401                         error = retval; 
402                 goto out_close;
403         }
404
405         total_size = total_mapping_size(elf_phdata, interp_elf_ex->e_phnum);
406         if (!total_size)
407                 goto out_close;
408
409         eppnt = elf_phdata;
410         for (i = 0; i < interp_elf_ex->e_phnum; i++, eppnt++) {
411                 if (eppnt->p_type == PT_LOAD) {
412                         int elf_type = MAP_PRIVATE | MAP_DENYWRITE;
413                         int elf_prot = 0;
414                         unsigned long vaddr = 0;
415                         unsigned long k, map_addr;
416
417                         if (eppnt->p_flags & PF_R)
418                                 elf_prot = PROT_READ;
419                         if (eppnt->p_flags & PF_W)
420                                 elf_prot |= PROT_WRITE;
421                         if (eppnt->p_flags & PF_X)
422                                 elf_prot |= PROT_EXEC;
423                         vaddr = eppnt->p_vaddr;
424                         if (interp_elf_ex->e_type == ET_EXEC || load_addr_set)
425                                 elf_type |= MAP_FIXED;
426                         else if (no_base && interp_elf_ex->e_type == ET_DYN)
427                                 load_addr = -vaddr;
428
429                         map_addr = elf_map(interpreter, load_addr + vaddr,
430                                            eppnt, elf_prot, elf_type, total_size);
431                         total_size = 0;
432                         if (!*interp_map_addr)
433                                 *interp_map_addr = map_addr;
434                         error = map_addr;
435                         if (BAD_ADDR(map_addr))
436                                 goto out_close;
437
438                         if (!load_addr_set &&
439                             interp_elf_ex->e_type == ET_DYN) {
440                                 load_addr = map_addr - ELF_PAGESTART(vaddr);
441                                 load_addr_set = 1;
442                         }
443
444                         /*
445                          * Check to see if the section's size will overflow the
446                          * allowed task size. Note that p_filesz must always be
447                          * <= p_memsize so it's only necessary to check p_memsz.
448                          */
449                         k = load_addr + eppnt->p_vaddr;
450                         if (BAD_ADDR(k) ||
451                             eppnt->p_filesz > eppnt->p_memsz ||
452                             eppnt->p_memsz > TASK_SIZE ||
453                             TASK_SIZE - eppnt->p_memsz < k) {
454                                 error = -ENOMEM;
455                                 goto out_close;
456                         }
457
458                         /*
459                          * Find the end of the file mapping for this phdr, and
460                          * keep track of the largest address we see for this.
461                          */
462                         k = load_addr + eppnt->p_vaddr + eppnt->p_filesz;
463                         if (k > elf_bss)
464                                 elf_bss = k;
465
466                         /*
467                          * Do the same thing for the memory mapping - between
468                          * elf_bss and last_bss is the bss section.
469                          */
470                         k = load_addr + eppnt->p_memsz + eppnt->p_vaddr;
471                         if (k > last_bss)
472                                 last_bss = k;
473                 }
474         }
475
476         /*
477          * Now fill out the bss section.  First pad the last page up
478          * to the page boundary, and then perform a mmap to make sure
479          * that there are zero-mapped pages up to and including the 
480          * last bss page.
481          */
482         if (padzero(elf_bss)) {
483                 error = -EFAULT;
484                 goto out_close;
485         }
486
487         /* What we have mapped so far */
488         elf_bss = ELF_PAGESTART(elf_bss + ELF_MIN_ALIGN - 1);
489
490         /* Map the last of the bss segment */
491         if (last_bss > elf_bss) {
492                 down_write(&current->mm->mmap_sem);
493                 error = do_brk(elf_bss, last_bss - elf_bss);
494                 up_write(&current->mm->mmap_sem);
495                 if (BAD_ADDR(error))
496                         goto out_close;
497         }
498
499         error = load_addr;
500
501 out_close:
502         kfree(elf_phdata);
503 out:
504         return error;
505 }
506
507 static unsigned long load_aout_interp(struct exec *interp_ex,
508                 struct file *interpreter)
509 {
510         unsigned long text_data, elf_entry = ~0UL;
511         char __user * addr;
512         loff_t offset;
513
514         current->mm->end_code = interp_ex->a_text;
515         text_data = interp_ex->a_text + interp_ex->a_data;
516         current->mm->end_data = text_data;
517         current->mm->brk = interp_ex->a_bss + text_data;
518
519         switch (N_MAGIC(*interp_ex)) {
520         case OMAGIC:
521                 offset = 32;
522                 addr = (char __user *)0;
523                 break;
524         case ZMAGIC:
525         case QMAGIC:
526                 offset = N_TXTOFF(*interp_ex);
527                 addr = (char __user *)N_TXTADDR(*interp_ex);
528                 break;
529         default:
530                 goto out;
531         }
532
533         down_write(&current->mm->mmap_sem);     
534         do_brk(0, text_data);
535         up_write(&current->mm->mmap_sem);
536         if (!interpreter->f_op || !interpreter->f_op->read)
537                 goto out;
538         if (interpreter->f_op->read(interpreter, addr, text_data, &offset) < 0)
539                 goto out;
540         flush_icache_range((unsigned long)addr,
541                            (unsigned long)addr + text_data);
542
543         down_write(&current->mm->mmap_sem);     
544         do_brk(ELF_PAGESTART(text_data + ELF_MIN_ALIGN - 1),
545                 interp_ex->a_bss);
546         up_write(&current->mm->mmap_sem);
547         elf_entry = interp_ex->a_entry;
548
549 out:
550         return elf_entry;
551 }
552
553 /*
554  * These are the functions used to load ELF style executables and shared
555  * libraries.  There is no binary dependent code anywhere else.
556  */
557
558 #define INTERPRETER_NONE 0
559 #define INTERPRETER_AOUT 1
560 #define INTERPRETER_ELF 2
561
562 #ifndef STACK_RND_MASK
563 #define STACK_RND_MASK 0x7ff            /* with 4K pages 8MB of VA */
564 #endif
565
566 static unsigned long randomize_stack_top(unsigned long stack_top)
567 {
568         unsigned int random_variable = 0;
569
570         if (current->flags & PF_RANDOMIZE) {
571                 random_variable = get_random_int() & STACK_RND_MASK;
572                 random_variable <<= PAGE_SHIFT;
573         }
574 #ifdef CONFIG_STACK_GROWSUP
575         return PAGE_ALIGN(stack_top) + random_variable;
576 #else
577         return PAGE_ALIGN(stack_top) - random_variable;
578 #endif
579 }
580
581 static int load_elf_binary(struct linux_binprm *bprm, struct pt_regs *regs)
582 {
583         struct file *interpreter = NULL; /* to shut gcc up */
584         unsigned long load_addr = 0, load_bias = 0;
585         int load_addr_set = 0;
586         char * elf_interpreter = NULL;
587         unsigned int interpreter_type = INTERPRETER_NONE;
588         unsigned char ibcs2_interpreter = 0;
589         unsigned long error;
590         struct elf_phdr *elf_ppnt, *elf_phdata;
591         unsigned long elf_bss, elf_brk;
592         int elf_exec_fileno;
593         int retval, i;
594         unsigned int size;
595         unsigned long elf_entry, interp_load_addr = 0, interp_map_addr = 0;
596         unsigned long start_code, end_code, start_data, end_data;
597         unsigned long reloc_func_desc = 0;
598         char passed_fileno[6];
599         struct files_struct *files;
600         int have_pt_gnu_stack, executable_stack;
601         unsigned long def_flags = 0;
602         struct {
603                 struct elfhdr elf_ex;
604                 struct elfhdr interp_elf_ex;
605                 struct exec interp_ex;
606         } *loc;
607
608         loc = kmalloc(sizeof(*loc), GFP_KERNEL);
609         if (!loc) {
610                 retval = -ENOMEM;
611                 goto out_ret;
612         }
613         
614         /* Get the exec-header */
615         loc->elf_ex = *((struct elfhdr *)bprm->buf);
616
617         retval = -ENOEXEC;
618         /* First of all, some simple consistency checks */
619         if (memcmp(loc->elf_ex.e_ident, ELFMAG, SELFMAG) != 0)
620                 goto out;
621
622         if (loc->elf_ex.e_type != ET_EXEC && loc->elf_ex.e_type != ET_DYN)
623                 goto out;
624         if (!elf_check_arch(&loc->elf_ex))
625                 goto out;
626         if (!bprm->file->f_op||!bprm->file->f_op->mmap)
627                 goto out;
628
629         /* Now read in all of the header information */
630         if (loc->elf_ex.e_phentsize != sizeof(struct elf_phdr))
631                 goto out;
632         if (loc->elf_ex.e_phnum < 1 ||
633                 loc->elf_ex.e_phnum > 65536U / sizeof(struct elf_phdr))
634                 goto out;
635         size = loc->elf_ex.e_phnum * sizeof(struct elf_phdr);
636         retval = -ENOMEM;
637         elf_phdata = kmalloc(size, GFP_KERNEL);
638         if (!elf_phdata)
639                 goto out;
640
641         retval = kernel_read(bprm->file, loc->elf_ex.e_phoff,
642                              (char *)elf_phdata, size);
643         if (retval != size) {
644                 if (retval >= 0)
645                         retval = -EIO;
646                 goto out_free_ph;
647         }
648
649         files = current->files; /* Refcounted so ok */
650         retval = unshare_files();
651         if (retval < 0)
652                 goto out_free_ph;
653         if (files == current->files) {
654                 put_files_struct(files);
655                 files = NULL;
656         }
657
658         /* exec will make our files private anyway, but for the a.out
659            loader stuff we need to do it earlier */
660         retval = get_unused_fd();
661         if (retval < 0)
662                 goto out_free_fh;
663         get_file(bprm->file);
664         fd_install(elf_exec_fileno = retval, bprm->file);
665
666         elf_ppnt = elf_phdata;
667         elf_bss = 0;
668         elf_brk = 0;
669
670         start_code = ~0UL;
671         end_code = 0;
672         start_data = 0;
673         end_data = 0;
674
675         for (i = 0; i < loc->elf_ex.e_phnum; i++) {
676                 if (elf_ppnt->p_type == PT_INTERP) {
677                         /* This is the program interpreter used for
678                          * shared libraries - for now assume that this
679                          * is an a.out format binary
680                          */
681                         retval = -ENOEXEC;
682                         if (elf_ppnt->p_filesz > PATH_MAX || 
683                             elf_ppnt->p_filesz < 2)
684                                 goto out_free_file;
685
686                         retval = -ENOMEM;
687                         elf_interpreter = kmalloc(elf_ppnt->p_filesz,
688                                                   GFP_KERNEL);
689                         if (!elf_interpreter)
690                                 goto out_free_file;
691
692                         retval = kernel_read(bprm->file, elf_ppnt->p_offset,
693                                              elf_interpreter,
694                                              elf_ppnt->p_filesz);
695                         if (retval != elf_ppnt->p_filesz) {
696                                 if (retval >= 0)
697                                         retval = -EIO;
698                                 goto out_free_interp;
699                         }
700                         /* make sure path is NULL terminated */
701                         retval = -ENOEXEC;
702                         if (elf_interpreter[elf_ppnt->p_filesz - 1] != '\0')
703                                 goto out_free_interp;
704
705                         /* If the program interpreter is one of these two,
706                          * then assume an iBCS2 image. Otherwise assume
707                          * a native linux image.
708                          */
709                         if (strcmp(elf_interpreter,"/usr/lib/libc.so.1") == 0 ||
710                             strcmp(elf_interpreter,"/usr/lib/ld.so.1") == 0)
711                                 ibcs2_interpreter = 1;
712
713                         /*
714                          * The early SET_PERSONALITY here is so that the lookup
715                          * for the interpreter happens in the namespace of the 
716                          * to-be-execed image.  SET_PERSONALITY can select an
717                          * alternate root.
718                          *
719                          * However, SET_PERSONALITY is NOT allowed to switch
720                          * this task into the new images's memory mapping
721                          * policy - that is, TASK_SIZE must still evaluate to
722                          * that which is appropriate to the execing application.
723                          * This is because exit_mmap() needs to have TASK_SIZE
724                          * evaluate to the size of the old image.
725                          *
726                          * So if (say) a 64-bit application is execing a 32-bit
727                          * application it is the architecture's responsibility
728                          * to defer changing the value of TASK_SIZE until the
729                          * switch really is going to happen - do this in
730                          * flush_thread().      - akpm
731                          */
732                         SET_PERSONALITY(loc->elf_ex, ibcs2_interpreter);
733
734                         interpreter = open_exec(elf_interpreter);
735                         retval = PTR_ERR(interpreter);
736                         if (IS_ERR(interpreter))
737                                 goto out_free_interp;
738                         retval = kernel_read(interpreter, 0, bprm->buf,
739                                              BINPRM_BUF_SIZE);
740                         if (retval != BINPRM_BUF_SIZE) {
741                                 if (retval >= 0)
742                                         retval = -EIO;
743                                 goto out_free_dentry;
744                         }
745
746                         /* Get the exec headers */
747                         loc->interp_ex = *((struct exec *)bprm->buf);
748                         loc->interp_elf_ex = *((struct elfhdr *)bprm->buf);
749                         break;
750                 }
751                 elf_ppnt++;
752         }
753
754         elf_ppnt = elf_phdata;
755         executable_stack = EXSTACK_DEFAULT;
756
757         for (i = 0; i < loc->elf_ex.e_phnum; i++, elf_ppnt++)
758                 if (elf_ppnt->p_type == PT_GNU_STACK) {
759                         if (elf_ppnt->p_flags & PF_X)
760                                 executable_stack = EXSTACK_ENABLE_X;
761                         else
762                                 executable_stack = EXSTACK_DISABLE_X;
763                         break;
764                 }
765         have_pt_gnu_stack = (i < loc->elf_ex.e_phnum);
766
767         if (current->personality == PER_LINUX && (exec_shield & 2)) {
768                 executable_stack = EXSTACK_DISABLE_X;
769                 current->flags |= PF_RANDOMIZE;
770         }
771
772         /* Some simple consistency checks for the interpreter */
773         if (elf_interpreter) {
774                 interpreter_type = INTERPRETER_ELF | INTERPRETER_AOUT;
775
776                 /* Now figure out which format our binary is */
777                 if ((N_MAGIC(loc->interp_ex) != OMAGIC) &&
778                     (N_MAGIC(loc->interp_ex) != ZMAGIC) &&
779                     (N_MAGIC(loc->interp_ex) != QMAGIC))
780                         interpreter_type = INTERPRETER_ELF;
781
782                 if (memcmp(loc->interp_elf_ex.e_ident, ELFMAG, SELFMAG) != 0)
783                         interpreter_type &= ~INTERPRETER_ELF;
784
785                 retval = -ELIBBAD;
786                 if (!interpreter_type)
787                         goto out_free_dentry;
788
789                 /* Make sure only one type was selected */
790                 if ((interpreter_type & INTERPRETER_ELF) &&
791                      interpreter_type != INTERPRETER_ELF) {
792                         // FIXME - ratelimit this before re-enabling
793                         // printk(KERN_WARNING "ELF: Ambiguous type, using ELF\n");
794                         interpreter_type = INTERPRETER_ELF;
795                 }
796                 /* Verify the interpreter has a valid arch */
797                 if ((interpreter_type == INTERPRETER_ELF) &&
798                     !elf_check_arch(&loc->interp_elf_ex))
799                         goto out_free_dentry;
800         } else {
801                 /* Executables without an interpreter also need a personality  */
802                 SET_PERSONALITY(loc->elf_ex, ibcs2_interpreter);
803         }
804
805         /* OK, we are done with that, now set up the arg stuff,
806            and then start this sucker up */
807         if ((!bprm->sh_bang) && (interpreter_type == INTERPRETER_AOUT)) {
808                 char *passed_p = passed_fileno;
809                 sprintf(passed_fileno, "%d", elf_exec_fileno);
810
811                 if (elf_interpreter) {
812                         retval = copy_strings_kernel(1, &passed_p, bprm);
813                         if (retval)
814                                 goto out_free_dentry; 
815                         bprm->argc++;
816                 }
817         }
818
819         /* Flush all traces of the currently running executable */
820         retval = flush_old_exec(bprm);
821         if (retval)
822                 goto out_free_dentry;
823
824 #ifdef __i386__
825         /*
826          * Turn off the CS limit completely if exec-shield disabled or
827          * NX active:
828          */
829         if (!exec_shield || executable_stack != EXSTACK_DISABLE_X || nx_enabled)
830                 arch_add_exec_range(current->mm, -1);
831 #endif
832
833         /* Discard our unneeded old files struct */
834         if (files) {
835                 put_files_struct(files);
836                 files = NULL;
837         }
838
839         /* OK, This is the point of no return */
840         current->mm->start_data = 0;
841         current->mm->end_data = 0;
842         current->mm->end_code = 0;
843         current->mm->mmap = NULL;
844         current->flags &= ~PF_FORKNOEXEC;
845         current->mm->def_flags = def_flags;
846
847         /* Do this immediately, since STACK_TOP as used in setup_arg_pages
848            may depend on the personality.  */
849         SET_PERSONALITY(loc->elf_ex, ibcs2_interpreter);
850         if (!(exec_shield & 2) &&
851                         elf_read_implies_exec(loc->elf_ex, executable_stack))
852                 current->personality |= READ_IMPLIES_EXEC;
853
854         if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space)
855                 current->flags |= PF_RANDOMIZE;
856         arch_pick_mmap_layout(current->mm);
857
858         /* Do this so that we can load the interpreter, if need be.  We will
859            change some of these later */
860         current->mm->free_area_cache = current->mm->mmap_base;
861         current->mm->cached_hole_size = 0;
862         retval = setup_arg_pages(bprm, randomize_stack_top(STACK_TOP),
863                                  executable_stack);
864         if (retval < 0) {
865                 send_sig(SIGKILL, current, 0);
866                 goto out_free_dentry;
867         }
868         
869         current->mm->start_stack = bprm->p;
870
871         /* Now we do a little grungy work by mmaping the ELF image into
872            the correct location in memory.
873          */
874         for(i = 0, elf_ppnt = elf_phdata;
875             i < loc->elf_ex.e_phnum; i++, elf_ppnt++) {
876                 int elf_prot = 0, elf_flags;
877                 unsigned long k, vaddr;
878
879                 if (elf_ppnt->p_type != PT_LOAD)
880                         continue;
881
882                 if (unlikely (elf_brk > elf_bss)) {
883                         unsigned long nbyte;
884                     
885                         /* There was a PT_LOAD segment with p_memsz > p_filesz
886                            before this one. Map anonymous pages, if needed,
887                            and clear the area.  */
888                         retval = set_brk (elf_bss + load_bias,
889                                           elf_brk + load_bias);
890                         if (retval) {
891                                 send_sig(SIGKILL, current, 0);
892                                 goto out_free_dentry;
893                         }
894                         nbyte = ELF_PAGEOFFSET(elf_bss);
895                         if (nbyte) {
896                                 nbyte = ELF_MIN_ALIGN - nbyte;
897                                 if (nbyte > elf_brk - elf_bss)
898                                         nbyte = elf_brk - elf_bss;
899                                 if (clear_user((void __user *)elf_bss +
900                                                         load_bias, nbyte)) {
901                                         /*
902                                          * This bss-zeroing can fail if the ELF
903                                          * file specifies odd protections. So
904                                          * we don't check the return value
905                                          */
906                                 }
907                         }
908                 }
909
910                 if (elf_ppnt->p_flags & PF_R)
911                         elf_prot |= PROT_READ;
912                 if (elf_ppnt->p_flags & PF_W)
913                         elf_prot |= PROT_WRITE;
914                 if (elf_ppnt->p_flags & PF_X)
915                         elf_prot |= PROT_EXEC;
916
917                 elf_flags = MAP_PRIVATE | MAP_DENYWRITE | MAP_EXECUTABLE;
918
919                 vaddr = elf_ppnt->p_vaddr;
920                 if (loc->elf_ex.e_type == ET_EXEC || load_addr_set)
921                         elf_flags |= MAP_FIXED;
922                 else if (loc->elf_ex.e_type == ET_DYN)
923 #ifdef __i386__
924                         load_bias = 0;
925 #else
926                         load_bias = ELF_PAGESTART(ELF_ET_DYN_BASE - vaddr);
927 #endif
928
929                 error = elf_map(bprm->file, load_bias + vaddr, elf_ppnt,
930                                 elf_prot, elf_flags, 0);
931                 if (BAD_ADDR(error)) {
932                         send_sig(SIGKILL, current, 0);
933                         goto out_free_dentry;
934                 }
935
936                 if (!load_addr_set) {
937                         load_addr_set = 1;
938                         load_addr = (elf_ppnt->p_vaddr - elf_ppnt->p_offset);
939                         if (loc->elf_ex.e_type == ET_DYN) {
940                                 load_bias += error -
941                                              ELF_PAGESTART(load_bias + vaddr);
942                                 load_addr += load_bias;
943                                 reloc_func_desc = load_bias;
944                         }
945                 }
946                 k = elf_ppnt->p_vaddr;
947                 if (k < start_code)
948                         start_code = k;
949                 if (start_data < k)
950                         start_data = k;
951
952                 /*
953                  * Check to see if the section's size will overflow the
954                  * allowed task size. Note that p_filesz must always be
955                  * <= p_memsz so it is only necessary to check p_memsz.
956                  */
957                 if (BAD_ADDR(k) || elf_ppnt->p_filesz > elf_ppnt->p_memsz ||
958                     elf_ppnt->p_memsz > TASK_SIZE ||
959                     TASK_SIZE - elf_ppnt->p_memsz < k) {
960                         /* set_brk can never work. Avoid overflows. */
961                         send_sig(SIGKILL, current, 0);
962                         goto out_free_dentry;
963                 }
964
965                 k = elf_ppnt->p_vaddr + elf_ppnt->p_filesz;
966
967                 if (k > elf_bss)
968                         elf_bss = k;
969                 if ((elf_ppnt->p_flags & PF_X) && end_code < k)
970                         end_code = k;
971                 if (end_data < k)
972                         end_data = k;
973                 k = elf_ppnt->p_vaddr + elf_ppnt->p_memsz;
974                 if (k > elf_brk)
975                         elf_brk = k;
976         }
977
978         loc->elf_ex.e_entry += load_bias;
979         elf_bss += load_bias;
980         elf_brk += load_bias;
981         start_code += load_bias;
982         end_code += load_bias;
983         start_data += load_bias;
984         end_data += load_bias;
985
986         /* Calling set_brk effectively mmaps the pages that we need
987          * for the bss and break sections.  We must do this before
988          * mapping in the interpreter, to make sure it doesn't wind
989          * up getting placed where the bss needs to go.
990          */
991         retval = set_brk(elf_bss, elf_brk);
992         if (retval) {
993                 send_sig(SIGKILL, current, 0);
994                 goto out_free_dentry;
995         }
996         if (likely(elf_bss != elf_brk) && unlikely(padzero(elf_bss))) {
997                 send_sig(SIGSEGV, current, 0);
998                 retval = -EFAULT; /* Nobody gets to see this, but.. */
999                 goto out_free_dentry;
1000         }
1001
1002         if (elf_interpreter) {
1003                 if (interpreter_type == INTERPRETER_AOUT)
1004                         elf_entry = load_aout_interp(&loc->interp_ex,
1005                                                      interpreter);
1006                 else {
1007                         elf_entry = load_elf_interp(&loc->interp_elf_ex,
1008                                                     interpreter,
1009                                                     &interp_map_addr,
1010                                                     load_bias);
1011                         if (!BAD_ADDR(elf_entry)) {
1012                                 /* load_elf_interp() returns relocation adjustment */
1013                                 interp_load_addr = elf_entry;
1014                                 elf_entry += loc->interp_elf_ex.e_entry;
1015                         }
1016                 }
1017                 if (BAD_ADDR(elf_entry)) {
1018                         force_sig(SIGSEGV, current);
1019                         retval = IS_ERR((void *)elf_entry) ?
1020                                         (int)elf_entry : -EINVAL;
1021                         goto out_free_dentry;
1022                 }
1023                 reloc_func_desc = interp_load_addr;
1024
1025                 allow_write_access(interpreter);
1026                 fput(interpreter);
1027                 kfree(elf_interpreter);
1028         } else {
1029                 elf_entry = loc->elf_ex.e_entry;
1030                 if (BAD_ADDR(elf_entry)) {
1031                         force_sig(SIGSEGV, current);
1032                         retval = -EINVAL;
1033                         goto out_free_dentry;
1034                 }
1035         }
1036
1037         if (interpreter_type != INTERPRETER_AOUT)
1038                 sys_close(elf_exec_fileno);
1039
1040         set_binfmt(&elf_format);
1041
1042 #ifdef ARCH_HAS_SETUP_ADDITIONAL_PAGES
1043         retval = arch_setup_additional_pages(bprm, executable_stack,
1044                         start_code, interp_map_addr);
1045         if (retval < 0) {
1046                 send_sig(SIGKILL, current, 0);
1047                 goto out_free_fh;
1048         }
1049 #endif /* ARCH_HAS_SETUP_ADDITIONAL_PAGES */
1050
1051         kfree(elf_phdata);
1052
1053         compute_creds(bprm);
1054         current->flags &= ~PF_FORKNOEXEC;
1055         create_elf_tables(bprm, &loc->elf_ex,
1056                           (interpreter_type == INTERPRETER_AOUT),
1057                           load_addr, interp_load_addr);
1058         /* N.B. passed_fileno might not be initialized? */
1059         if (interpreter_type == INTERPRETER_AOUT)
1060                 current->mm->arg_start += strlen(passed_fileno) + 1;
1061         current->mm->end_code = end_code;
1062         current->mm->start_code = start_code;
1063         current->mm->start_data = start_data;
1064         current->mm->end_data = end_data;
1065         current->mm->start_stack = bprm->p;
1066
1067 #ifdef __HAVE_ARCH_RANDOMIZE_BRK
1068         if (current->flags & PF_RANDOMIZE)
1069                 randomize_brk(elf_brk);
1070 #endif
1071         if (current->personality & MMAP_PAGE_ZERO) {
1072                 /* Why this, you ask???  Well SVr4 maps page 0 as read-only,
1073                    and some applications "depend" upon this behavior.
1074                    Since we do not have the power to recompile these, we
1075                    emulate the SVr4 behavior. Sigh. */
1076                 down_write(&current->mm->mmap_sem);
1077                 error = do_mmap(NULL, 0, PAGE_SIZE, PROT_READ | PROT_EXEC,
1078                                 MAP_FIXED | MAP_PRIVATE, 0);
1079                 up_write(&current->mm->mmap_sem);
1080         }
1081
1082 #ifdef ELF_PLAT_INIT
1083         /*
1084          * The ABI may specify that certain registers be set up in special
1085          * ways (on i386 %edx is the address of a DT_FINI function, for
1086          * example.  In addition, it may also specify (eg, PowerPC64 ELF)
1087          * that the e_entry field is the address of the function descriptor
1088          * for the startup routine, rather than the address of the startup
1089          * routine itself.  This macro performs whatever initialization to
1090          * the regs structure is required as well as any relocations to the
1091          * function descriptor entries when executing dynamically links apps.
1092          */
1093         ELF_PLAT_INIT(regs, reloc_func_desc);
1094 #endif
1095
1096         start_thread(regs, elf_entry, bprm->p);
1097         retval = 0;
1098 out:
1099         kfree(loc);
1100 out_ret:
1101         return retval;
1102
1103         /* error cleanup */
1104 out_free_dentry:
1105         allow_write_access(interpreter);
1106         if (interpreter)
1107                 fput(interpreter);
1108 out_free_interp:
1109         kfree(elf_interpreter);
1110 out_free_file:
1111         sys_close(elf_exec_fileno);
1112 out_free_fh:
1113         if (files) {
1114                 put_files_struct(current->files);
1115                 current->files = files;
1116         }
1117 out_free_ph:
1118         kfree(elf_phdata);
1119         goto out;
1120 }
1121
1122 /* This is really simpleminded and specialized - we are loading an
1123    a.out library that is given an ELF header. */
1124 static int load_elf_library(struct file *file)
1125 {
1126         struct elf_phdr *elf_phdata;
1127         struct elf_phdr *eppnt;
1128         unsigned long elf_bss, bss, len;
1129         int retval, error, i, j;
1130         struct elfhdr elf_ex;
1131
1132         error = -ENOEXEC;
1133         retval = kernel_read(file, 0, (char *)&elf_ex, sizeof(elf_ex));
1134         if (retval != sizeof(elf_ex))
1135                 goto out;
1136
1137         if (memcmp(elf_ex.e_ident, ELFMAG, SELFMAG) != 0)
1138                 goto out;
1139
1140         /* First of all, some simple consistency checks */
1141         if (elf_ex.e_type != ET_EXEC || elf_ex.e_phnum > 2 ||
1142             !elf_check_arch(&elf_ex) || !file->f_op || !file->f_op->mmap)
1143                 goto out;
1144
1145         /* Now read in all of the header information */
1146
1147         j = sizeof(struct elf_phdr) * elf_ex.e_phnum;
1148         /* j < ELF_MIN_ALIGN because elf_ex.e_phnum <= 2 */
1149
1150         error = -ENOMEM;
1151         elf_phdata = kmalloc(j, GFP_KERNEL);
1152         if (!elf_phdata)
1153                 goto out;
1154
1155         eppnt = elf_phdata;
1156         error = -ENOEXEC;
1157         retval = kernel_read(file, elf_ex.e_phoff, (char *)eppnt, j);
1158         if (retval != j)
1159                 goto out_free_ph;
1160
1161         for (j = 0, i = 0; i<elf_ex.e_phnum; i++)
1162                 if ((eppnt + i)->p_type == PT_LOAD)
1163                         j++;
1164         if (j != 1)
1165                 goto out_free_ph;
1166
1167         while (eppnt->p_type != PT_LOAD)
1168                 eppnt++;
1169
1170         /* Now use mmap to map the library into memory. */
1171         down_write(&current->mm->mmap_sem);
1172         error = do_mmap(file,
1173                         ELF_PAGESTART(eppnt->p_vaddr),
1174                         (eppnt->p_filesz +
1175                          ELF_PAGEOFFSET(eppnt->p_vaddr)),
1176                         PROT_READ | PROT_WRITE | PROT_EXEC,
1177                         MAP_FIXED | MAP_PRIVATE | MAP_DENYWRITE,
1178                         (eppnt->p_offset -
1179                          ELF_PAGEOFFSET(eppnt->p_vaddr)));
1180         up_write(&current->mm->mmap_sem);
1181         if (error != ELF_PAGESTART(eppnt->p_vaddr))
1182                 goto out_free_ph;
1183
1184         elf_bss = eppnt->p_vaddr + eppnt->p_filesz;
1185         if (padzero(elf_bss)) {
1186                 error = -EFAULT;
1187                 goto out_free_ph;
1188         }
1189
1190         len = ELF_PAGESTART(eppnt->p_filesz + eppnt->p_vaddr +
1191                             ELF_MIN_ALIGN - 1);
1192         bss = eppnt->p_memsz + eppnt->p_vaddr;
1193         if (bss > len) {
1194                 down_write(&current->mm->mmap_sem);
1195                 do_brk(len, bss - len);
1196                 up_write(&current->mm->mmap_sem);
1197         }
1198         error = 0;
1199
1200 out_free_ph:
1201         kfree(elf_phdata);
1202 out:
1203         return error;
1204 }
1205
1206 /*
1207  * Note that some platforms still use traditional core dumps and not
1208  * the ELF core dump.  Each platform can select it as appropriate.
1209  */
1210 #if defined(USE_ELF_CORE_DUMP) && defined(CONFIG_ELF_CORE)
1211
1212 /*
1213  * ELF core dumper
1214  *
1215  * Modelled on fs/exec.c:aout_core_dump()
1216  * Jeremy Fitzhardinge <jeremy@sw.oz.au>
1217  */
1218 /*
1219  * These are the only things you should do on a core-file: use only these
1220  * functions to write out all the necessary info.
1221  */
1222 static int dump_write(struct file *file, const void *addr, int nr)
1223 {
1224         return file->f_op->write(file, addr, nr, &file->f_pos) == nr;
1225 }
1226
1227 static int dump_seek(struct file *file, loff_t off)
1228 {
1229         if (file->f_op->llseek) {
1230                 if (file->f_op->llseek(file, off, 0) != off)
1231                         return 0;
1232         } else
1233                 file->f_pos = off;
1234         return 1;
1235 }
1236
1237 /*
1238  * Decide whether a segment is worth dumping; default is yes to be
1239  * sure (missing info is worse than too much; etc).
1240  * Personally I'd include everything, and use the coredump limit...
1241  *
1242  * I think we should skip something. But I am not sure how. H.J.
1243  */
1244 static int maydump(struct vm_area_struct *vma)
1245 {
1246         /* Do not dump I/O mapped devices or special mappings */
1247         if (vma->vm_flags & (VM_IO | VM_RESERVED))
1248                 return 0;
1249
1250         if (vma->vm_flags & VM_DONTEXPAND) /* Kludge for vDSO.  */
1251                 return 1;
1252
1253         /* Dump shared memory only if mapped from an anonymous file. */
1254         if (vma->vm_flags & VM_SHARED)
1255                 return vma->vm_file->f_dentry->d_inode->i_nlink == 0;
1256
1257         /* If it hasn't been written to, don't write it out */
1258         if (!vma->anon_vma)
1259                 return 0;
1260
1261         return 1;
1262 }
1263
1264 /* An ELF note in memory */
1265 struct memelfnote
1266 {
1267         const char *name;
1268         int type;
1269         unsigned int datasz;
1270         void *data;
1271 };
1272
1273 static int notesize(struct memelfnote *en)
1274 {
1275         int sz;
1276
1277         sz = sizeof(struct elf_note);
1278         sz += roundup(strlen(en->name) + 1, 4);
1279         sz += roundup(en->datasz, 4);
1280
1281         return sz;
1282 }
1283
1284 #define DUMP_WRITE(addr, nr)    \
1285         do { if (!dump_write(file, (addr), (nr))) return 0; } while(0)
1286 #define DUMP_SEEK(off)  \
1287         do { if (!dump_seek(file, (off))) return 0; } while(0)
1288
1289 static int writenote(struct memelfnote *men, struct file *file)
1290 {
1291         struct elf_note en;
1292
1293         en.n_namesz = strlen(men->name) + 1;
1294         en.n_descsz = men->datasz;
1295         en.n_type = men->type;
1296
1297         DUMP_WRITE(&en, sizeof(en));
1298         DUMP_WRITE(men->name, en.n_namesz);
1299         /* XXX - cast from long long to long to avoid need for libgcc.a */
1300         DUMP_SEEK(roundup((unsigned long)file->f_pos, 4));      /* XXX */
1301         DUMP_WRITE(men->data, men->datasz);
1302         DUMP_SEEK(roundup((unsigned long)file->f_pos, 4));      /* XXX */
1303
1304         return 1;
1305 }
1306 #undef DUMP_WRITE
1307 #undef DUMP_SEEK
1308
1309 #define DUMP_WRITE(addr, nr)    \
1310         if ((size += (nr)) > limit || !dump_write(file, (addr), (nr))) \
1311                 goto end_coredump;
1312 #define DUMP_SEEK(off)  \
1313         if (!dump_seek(file, (off))) \
1314                 goto end_coredump;
1315
1316 static void fill_elf_header(struct elfhdr *elf, int segs)
1317 {
1318         memcpy(elf->e_ident, ELFMAG, SELFMAG);
1319         elf->e_ident[EI_CLASS] = ELF_CLASS;
1320         elf->e_ident[EI_DATA] = ELF_DATA;
1321         elf->e_ident[EI_VERSION] = EV_CURRENT;
1322         elf->e_ident[EI_OSABI] = ELF_OSABI;
1323         memset(elf->e_ident+EI_PAD, 0, EI_NIDENT-EI_PAD);
1324
1325         elf->e_type = ET_CORE;
1326         elf->e_machine = ELF_ARCH;
1327         elf->e_version = EV_CURRENT;
1328         elf->e_entry = 0;
1329         elf->e_phoff = sizeof(struct elfhdr);
1330         elf->e_shoff = 0;
1331         elf->e_flags = ELF_CORE_EFLAGS;
1332         elf->e_ehsize = sizeof(struct elfhdr);
1333         elf->e_phentsize = sizeof(struct elf_phdr);
1334         elf->e_phnum = segs;
1335         elf->e_shentsize = 0;
1336         elf->e_shnum = 0;
1337         elf->e_shstrndx = 0;
1338         return;
1339 }
1340
1341 static void fill_elf_note_phdr(struct elf_phdr *phdr, int sz, off_t offset)
1342 {
1343         phdr->p_type = PT_NOTE;
1344         phdr->p_offset = offset;
1345         phdr->p_vaddr = 0;
1346         phdr->p_paddr = 0;
1347         phdr->p_filesz = sz;
1348         phdr->p_memsz = 0;
1349         phdr->p_flags = 0;
1350         phdr->p_align = 0;
1351         return;
1352 }
1353
1354 static void fill_note(struct memelfnote *note, const char *name, int type, 
1355                 unsigned int sz, void *data)
1356 {
1357         note->name = name;
1358         note->type = type;
1359         note->datasz = sz;
1360         note->data = data;
1361         return;
1362 }
1363
1364 /*
1365  * fill up all the fields in prstatus from the given task struct, except
1366  * registers which need to be filled up separately.
1367  */
1368 static void fill_prstatus(struct elf_prstatus *prstatus,
1369                 struct task_struct *p, long signr)
1370 {
1371         prstatus->pr_info.si_signo = prstatus->pr_cursig = signr;
1372         prstatus->pr_sigpend = p->pending.signal.sig[0];
1373         prstatus->pr_sighold = p->blocked.sig[0];
1374         prstatus->pr_pid = p->pid;
1375         prstatus->pr_ppid = p->parent->pid;
1376         prstatus->pr_pgrp = process_group(p);
1377         prstatus->pr_sid = p->signal->session;
1378         if (thread_group_leader(p)) {
1379                 /*
1380                  * This is the record for the group leader.  Add in the
1381                  * cumulative times of previous dead threads.  This total
1382                  * won't include the time of each live thread whose state
1383                  * is included in the core dump.  The final total reported
1384                  * to our parent process when it calls wait4 will include
1385                  * those sums as well as the little bit more time it takes
1386                  * this and each other thread to finish dying after the
1387                  * core dump synchronization phase.
1388                  */
1389                 cputime_to_timeval(cputime_add(p->utime, p->signal->utime),
1390                                    &prstatus->pr_utime);
1391                 cputime_to_timeval(cputime_add(p->stime, p->signal->stime),
1392                                    &prstatus->pr_stime);
1393         } else {
1394                 cputime_to_timeval(p->utime, &prstatus->pr_utime);
1395                 cputime_to_timeval(p->stime, &prstatus->pr_stime);
1396         }
1397         cputime_to_timeval(p->signal->cutime, &prstatus->pr_cutime);
1398         cputime_to_timeval(p->signal->cstime, &prstatus->pr_cstime);
1399 }
1400
1401 static int fill_psinfo(struct elf_prpsinfo *psinfo, struct task_struct *p,
1402                        struct mm_struct *mm)
1403 {
1404         unsigned int i, len;
1405         
1406         /* first copy the parameters from user space */
1407         memset(psinfo, 0, sizeof(struct elf_prpsinfo));
1408
1409         len = mm->arg_end - mm->arg_start;
1410         if (len >= ELF_PRARGSZ)
1411                 len = ELF_PRARGSZ-1;
1412         if (copy_from_user(&psinfo->pr_psargs,
1413                            (const char __user *)mm->arg_start, len))
1414                 return -EFAULT;
1415         for(i = 0; i < len; i++)
1416                 if (psinfo->pr_psargs[i] == 0)
1417                         psinfo->pr_psargs[i] = ' ';
1418         psinfo->pr_psargs[len] = 0;
1419
1420         psinfo->pr_pid = p->pid;
1421         psinfo->pr_ppid = p->parent->pid;
1422         psinfo->pr_pgrp = process_group(p);
1423         psinfo->pr_sid = p->signal->session;
1424
1425         i = p->state ? ffz(~p->state) + 1 : 0;
1426         psinfo->pr_state = i;
1427         psinfo->pr_sname = (i > 5) ? '.' : "RSDTZW"[i];
1428         psinfo->pr_zomb = psinfo->pr_sname == 'Z';
1429         psinfo->pr_nice = task_nice(p);
1430         psinfo->pr_flag = p->flags;
1431         SET_UID(psinfo->pr_uid, p->uid);
1432         SET_GID(psinfo->pr_gid, p->gid);
1433         strncpy(psinfo->pr_fname, p->comm, sizeof(psinfo->pr_fname));
1434         
1435         return 0;
1436 }
1437
1438 /* Here is the structure in which status of each thread is captured. */
1439 struct elf_thread_status
1440 {
1441         struct list_head list;
1442         struct elf_prstatus prstatus;   /* NT_PRSTATUS */
1443         elf_fpregset_t fpu;             /* NT_PRFPREG */
1444         struct task_struct *thread;
1445 #ifdef ELF_CORE_COPY_XFPREGS
1446         elf_fpxregset_t xfpu;           /* NT_PRXFPREG */
1447 #endif
1448         struct memelfnote notes[3];
1449         int num_notes;
1450 };
1451
1452 /*
1453  * In order to add the specific thread information for the elf file format,
1454  * we need to keep a linked list of every threads pr_status and then create
1455  * a single section for them in the final core file.
1456  */
1457 static int elf_dump_thread_status(long signr, struct elf_thread_status *t)
1458 {
1459         int sz = 0;
1460         struct task_struct *p = t->thread;
1461         t->num_notes = 0;
1462
1463         fill_prstatus(&t->prstatus, p, signr);
1464         elf_core_copy_task_regs(p, &t->prstatus.pr_reg);        
1465         
1466         fill_note(&t->notes[0], "CORE", NT_PRSTATUS, sizeof(t->prstatus),
1467                   &(t->prstatus));
1468         t->num_notes++;
1469         sz += notesize(&t->notes[0]);
1470
1471         if ((t->prstatus.pr_fpvalid = elf_core_copy_task_fpregs(p, NULL,
1472                                                                 &t->fpu))) {
1473                 fill_note(&t->notes[1], "CORE", NT_PRFPREG, sizeof(t->fpu),
1474                           &(t->fpu));
1475                 t->num_notes++;
1476                 sz += notesize(&t->notes[1]);
1477         }
1478
1479 #ifdef ELF_CORE_COPY_XFPREGS
1480         if (elf_core_copy_task_xfpregs(p, &t->xfpu)) {
1481                 fill_note(&t->notes[2], "LINUX", NT_PRXFPREG, sizeof(t->xfpu),
1482                           &t->xfpu);
1483                 t->num_notes++;
1484                 sz += notesize(&t->notes[2]);
1485         }
1486 #endif  
1487         return sz;
1488 }
1489
1490 /*
1491  * Actual dumper
1492  *
1493  * This is a two-pass process; first we find the offsets of the bits,
1494  * and then they are actually written out.  If we run out of core limit
1495  * we just truncate.
1496  */
1497 static int elf_core_dump(long signr, struct pt_regs *regs, struct file *file)
1498 {
1499 #define NUM_NOTES       6
1500         int has_dumped = 0;
1501         mm_segment_t fs;
1502         int segs;
1503         size_t size = 0;
1504         int i;
1505         struct vm_area_struct *vma;
1506         struct elfhdr *elf = NULL;
1507         off_t offset = 0, dataoff;
1508         unsigned long limit = current->signal->rlim[RLIMIT_CORE].rlim_cur;
1509         int numnote;
1510         struct memelfnote *notes = NULL;
1511         struct elf_prstatus *prstatus = NULL;   /* NT_PRSTATUS */
1512         struct elf_prpsinfo *psinfo = NULL;     /* NT_PRPSINFO */
1513         struct task_struct *g, *p;
1514         LIST_HEAD(thread_list);
1515         struct list_head *t;
1516         elf_fpregset_t *fpu = NULL;
1517 #ifdef ELF_CORE_COPY_XFPREGS
1518         elf_fpxregset_t *xfpu = NULL;
1519 #endif
1520         int thread_status_size = 0;
1521         elf_addr_t *auxv;
1522
1523         /*
1524          * We no longer stop all VM operations.
1525          * 
1526          * This is because those proceses that could possibly change map_count
1527          * or the mmap / vma pages are now blocked in do_exit on current
1528          * finishing this core dump.
1529          *
1530          * Only ptrace can touch these memory addresses, but it doesn't change
1531          * the map_count or the pages allocated. So no possibility of crashing
1532          * exists while dumping the mm->vm_next areas to the core file.
1533          */
1534   
1535         /* alloc memory for large data structures: too large to be on stack */
1536         elf = kmalloc(sizeof(*elf), GFP_KERNEL);
1537         if (!elf)
1538                 goto cleanup;
1539         prstatus = kmalloc(sizeof(*prstatus), GFP_KERNEL);
1540         if (!prstatus)
1541                 goto cleanup;
1542         psinfo = kmalloc(sizeof(*psinfo), GFP_KERNEL);
1543         if (!psinfo)
1544                 goto cleanup;
1545         notes = kmalloc(NUM_NOTES * sizeof(struct memelfnote), GFP_KERNEL);
1546         if (!notes)
1547                 goto cleanup;
1548         fpu = kmalloc(sizeof(*fpu), GFP_KERNEL);
1549         if (!fpu)
1550                 goto cleanup;
1551 #ifdef ELF_CORE_COPY_XFPREGS
1552         xfpu = kmalloc(sizeof(*xfpu), GFP_KERNEL);
1553         if (!xfpu)
1554                 goto cleanup;
1555 #endif
1556
1557         if (signr) {
1558                 struct elf_thread_status *tmp;
1559                 read_lock(&tasklist_lock);
1560                 do_each_thread(g,p)
1561                         if (current->mm == p->mm && current != p) {
1562                                 tmp = kzalloc(sizeof(*tmp), GFP_ATOMIC);
1563                                 if (!tmp) {
1564                                         read_unlock(&tasklist_lock);
1565                                         goto cleanup;
1566                                 }
1567                                 INIT_LIST_HEAD(&tmp->list);
1568                                 tmp->thread = p;
1569                                 list_add(&tmp->list, &thread_list);
1570                         }
1571                 while_each_thread(g,p);
1572                 read_unlock(&tasklist_lock);
1573                 list_for_each(t, &thread_list) {
1574                         struct elf_thread_status *tmp;
1575                         int sz;
1576
1577                         tmp = list_entry(t, struct elf_thread_status, list);
1578                         sz = elf_dump_thread_status(signr, tmp);
1579                         thread_status_size += sz;
1580                 }
1581         }
1582         /* now collect the dump for the current */
1583         memset(prstatus, 0, sizeof(*prstatus));
1584         fill_prstatus(prstatus, current, signr);
1585         elf_core_copy_regs(&prstatus->pr_reg, regs);
1586         
1587         segs = current->mm->map_count;
1588 #ifdef ELF_CORE_EXTRA_PHDRS
1589         segs += ELF_CORE_EXTRA_PHDRS;
1590 #endif
1591
1592         /* Set up header */
1593         fill_elf_header(elf, segs + 1); /* including notes section */
1594
1595         has_dumped = 1;
1596         current->flags |= PF_DUMPCORE;
1597
1598         /*
1599          * Set up the notes in similar form to SVR4 core dumps made
1600          * with info from their /proc.
1601          */
1602
1603         fill_note(notes + 0, "CORE", NT_PRSTATUS, sizeof(*prstatus), prstatus);
1604         fill_psinfo(psinfo, current->group_leader, current->mm);
1605         fill_note(notes + 1, "CORE", NT_PRPSINFO, sizeof(*psinfo), psinfo);
1606         
1607         numnote = 2;
1608
1609         auxv = (elf_addr_t *)current->mm->saved_auxv;
1610
1611         i = 0;
1612         do
1613                 i += 2;
1614         while (auxv[i - 2] != AT_NULL);
1615         fill_note(&notes[numnote++], "CORE", NT_AUXV,
1616                   i * sizeof(elf_addr_t), auxv);
1617
1618         /* Try to dump the FPU. */
1619         if ((prstatus->pr_fpvalid =
1620              elf_core_copy_task_fpregs(current, regs, fpu)))
1621                 fill_note(notes + numnote++,
1622                           "CORE", NT_PRFPREG, sizeof(*fpu), fpu);
1623 #ifdef ELF_CORE_COPY_XFPREGS
1624         if (elf_core_copy_task_xfpregs(current, xfpu))
1625                 fill_note(notes + numnote++,
1626                           "LINUX", NT_PRXFPREG, sizeof(*xfpu), xfpu);
1627 #endif  
1628   
1629         fs = get_fs();
1630         set_fs(KERNEL_DS);
1631
1632         DUMP_WRITE(elf, sizeof(*elf));
1633         offset += sizeof(*elf);                         /* Elf header */
1634         offset += (segs+1) * sizeof(struct elf_phdr);   /* Program headers */
1635
1636         /* Write notes phdr entry */
1637         {
1638                 struct elf_phdr phdr;
1639                 int sz = 0;
1640
1641                 for (i = 0; i < numnote; i++)
1642                         sz += notesize(notes + i);
1643                 
1644                 sz += thread_status_size;
1645
1646                 fill_elf_note_phdr(&phdr, sz, offset);
1647                 offset += sz;
1648                 DUMP_WRITE(&phdr, sizeof(phdr));
1649         }
1650
1651         /* Page-align dumped data */
1652         dataoff = offset = roundup(offset, ELF_EXEC_PAGESIZE);
1653
1654         /* Write program headers for segments dump */
1655         for (vma = current->mm->mmap; vma != NULL; vma = vma->vm_next) {
1656                 struct elf_phdr phdr;
1657                 size_t sz;
1658
1659                 sz = vma->vm_end - vma->vm_start;
1660
1661                 phdr.p_type = PT_LOAD;
1662                 phdr.p_offset = offset;
1663                 phdr.p_vaddr = vma->vm_start;
1664                 phdr.p_paddr = 0;
1665                 phdr.p_filesz = maydump(vma) ? sz : 0;
1666                 phdr.p_memsz = sz;
1667                 offset += phdr.p_filesz;
1668                 phdr.p_flags = vma->vm_flags & VM_READ ? PF_R : 0;
1669                 if (vma->vm_flags & VM_WRITE)
1670                         phdr.p_flags |= PF_W;
1671                 if (vma->vm_flags & VM_EXEC)
1672                         phdr.p_flags |= PF_X;
1673                 phdr.p_align = ELF_EXEC_PAGESIZE;
1674
1675                 DUMP_WRITE(&phdr, sizeof(phdr));
1676         }
1677
1678 #ifdef ELF_CORE_WRITE_EXTRA_PHDRS
1679         ELF_CORE_WRITE_EXTRA_PHDRS;
1680 #endif
1681
1682         /* write out the notes section */
1683         for (i = 0; i < numnote; i++)
1684                 if (!writenote(notes + i, file))
1685                         goto end_coredump;
1686
1687         /* write out the thread status notes section */
1688         list_for_each(t, &thread_list) {
1689                 struct elf_thread_status *tmp =
1690                                 list_entry(t, struct elf_thread_status, list);
1691
1692                 for (i = 0; i < tmp->num_notes; i++)
1693                         if (!writenote(&tmp->notes[i], file))
1694                                 goto end_coredump;
1695         }
1696  
1697         DUMP_SEEK(dataoff);
1698
1699         for (vma = current->mm->mmap; vma != NULL; vma = vma->vm_next) {
1700                 unsigned long addr;
1701
1702                 if (!maydump(vma))
1703                         continue;
1704
1705                 for (addr = vma->vm_start;
1706                      addr < vma->vm_end;
1707                      addr += PAGE_SIZE) {
1708                         struct page *page;
1709                         struct vm_area_struct *vma;
1710
1711                         if (get_user_pages(current, current->mm, addr, 1, 0, 1,
1712                                                 &page, &vma) <= 0) {
1713                                 DUMP_SEEK(file->f_pos + PAGE_SIZE);
1714                         } else {
1715                                 if (page == ZERO_PAGE(addr)) {
1716                                         DUMP_SEEK(file->f_pos + PAGE_SIZE);
1717                                 } else {
1718                                         void *kaddr;
1719                                         flush_cache_page(vma, addr,
1720                                                          page_to_pfn(page));
1721                                         kaddr = kmap(page);
1722                                         if ((size += PAGE_SIZE) > limit ||
1723                                             !dump_write(file, kaddr,
1724                                             PAGE_SIZE)) {
1725                                                 kunmap(page);
1726                                                 page_cache_release(page);
1727                                                 goto end_coredump;
1728                                         }
1729                                         kunmap(page);
1730                                 }
1731                                 page_cache_release(page);
1732                         }
1733                 }
1734         }
1735
1736 #ifdef ELF_CORE_WRITE_EXTRA_DATA
1737         ELF_CORE_WRITE_EXTRA_DATA;
1738 #endif
1739
1740         if ((off_t)file->f_pos != offset) {
1741                 /* Sanity check */
1742                 printk(KERN_WARNING
1743                        "elf_core_dump: file->f_pos (%ld) != offset (%ld)\n",
1744                        (off_t)file->f_pos, offset);
1745         }
1746
1747 end_coredump:
1748         set_fs(fs);
1749
1750 cleanup:
1751         while (!list_empty(&thread_list)) {
1752                 struct list_head *tmp = thread_list.next;
1753                 list_del(tmp);
1754                 kfree(list_entry(tmp, struct elf_thread_status, list));
1755         }
1756
1757         kfree(elf);
1758         kfree(prstatus);
1759         kfree(psinfo);
1760         kfree(notes);
1761         kfree(fpu);
1762 #ifdef ELF_CORE_COPY_XFPREGS
1763         kfree(xfpu);
1764 #endif
1765         return has_dumped;
1766 #undef NUM_NOTES
1767 }
1768
1769 #endif          /* USE_ELF_CORE_DUMP */
1770
1771 static int __init init_elf_binfmt(void)
1772 {
1773         return register_binfmt(&elf_format);
1774 }
1775
1776 static void __exit exit_elf_binfmt(void)
1777 {
1778         /* Remove the COFF and ELF loaders. */
1779         unregister_binfmt(&elf_format);
1780 }
1781
1782 core_initcall(init_elf_binfmt);
1783 module_exit(exit_elf_binfmt);
1784 MODULE_LICENSE("GPL");