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