863250157aa753a0bfdf16f8b1299247bae657fe
[linux-2.6-microblaze.git] / fs / binfmt_elf_fdpic.c
1 /* binfmt_elf_fdpic.c: FDPIC ELF binary format
2  *
3  * Copyright (C) 2003, 2004, 2006 Red Hat, Inc. All Rights Reserved.
4  * Written by David Howells (dhowells@redhat.com)
5  * Derived from binfmt_elf.c
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version
10  * 2 of the License, or (at your option) any later version.
11  */
12
13 #include <linux/module.h>
14
15 #include <linux/fs.h>
16 #include <linux/stat.h>
17 #include <linux/sched.h>
18 #include <linux/mm.h>
19 #include <linux/mman.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/slab.h>
27 #include <linux/pagemap.h>
28 #include <linux/security.h>
29 #include <linux/highmem.h>
30 #include <linux/highuid.h>
31 #include <linux/personality.h>
32 #include <linux/ptrace.h>
33 #include <linux/init.h>
34 #include <linux/elf.h>
35 #include <linux/elf-fdpic.h>
36 #include <linux/elfcore.h>
37 #include <linux/coredump.h>
38 #include <linux/dax.h>
39
40 #include <asm/uaccess.h>
41 #include <asm/param.h>
42 #include <asm/pgalloc.h>
43
44 typedef char *elf_caddr_t;
45
46 #if 0
47 #define kdebug(fmt, ...) printk("FDPIC "fmt"\n" ,##__VA_ARGS__ )
48 #else
49 #define kdebug(fmt, ...) do {} while(0)
50 #endif
51
52 #if 0
53 #define kdcore(fmt, ...) printk("FDPIC "fmt"\n" ,##__VA_ARGS__ )
54 #else
55 #define kdcore(fmt, ...) do {} while(0)
56 #endif
57
58 MODULE_LICENSE("GPL");
59
60 static int load_elf_fdpic_binary(struct linux_binprm *);
61 static int elf_fdpic_fetch_phdrs(struct elf_fdpic_params *, struct file *);
62 static int elf_fdpic_map_file(struct elf_fdpic_params *, struct file *,
63                               struct mm_struct *, const char *);
64
65 static int create_elf_fdpic_tables(struct linux_binprm *, struct mm_struct *,
66                                    struct elf_fdpic_params *,
67                                    struct elf_fdpic_params *);
68
69 #ifndef CONFIG_MMU
70 static int elf_fdpic_transfer_args_to_stack(struct linux_binprm *,
71                                             unsigned long *);
72 static int elf_fdpic_map_file_constdisp_on_uclinux(struct elf_fdpic_params *,
73                                                    struct file *,
74                                                    struct mm_struct *);
75 #endif
76
77 static int elf_fdpic_map_file_by_direct_mmap(struct elf_fdpic_params *,
78                                              struct file *, struct mm_struct *);
79
80 #ifdef CONFIG_ELF_CORE
81 static int elf_fdpic_core_dump(struct coredump_params *cprm);
82 #endif
83
84 static struct linux_binfmt elf_fdpic_format = {
85         .module         = THIS_MODULE,
86         .load_binary    = load_elf_fdpic_binary,
87 #ifdef CONFIG_ELF_CORE
88         .core_dump      = elf_fdpic_core_dump,
89 #endif
90         .min_coredump   = ELF_EXEC_PAGESIZE,
91 };
92
93 static int __init init_elf_fdpic_binfmt(void)
94 {
95         register_binfmt(&elf_fdpic_format);
96         return 0;
97 }
98
99 static void __exit exit_elf_fdpic_binfmt(void)
100 {
101         unregister_binfmt(&elf_fdpic_format);
102 }
103
104 core_initcall(init_elf_fdpic_binfmt);
105 module_exit(exit_elf_fdpic_binfmt);
106
107 static int is_elf_fdpic(struct elfhdr *hdr, struct file *file)
108 {
109         if (memcmp(hdr->e_ident, ELFMAG, SELFMAG) != 0)
110                 return 0;
111         if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN)
112                 return 0;
113         if (!elf_check_arch(hdr) || !elf_check_fdpic(hdr))
114                 return 0;
115         if (!file->f_op->mmap)
116                 return 0;
117         return 1;
118 }
119
120 /*****************************************************************************/
121 /*
122  * read the program headers table into memory
123  */
124 static int elf_fdpic_fetch_phdrs(struct elf_fdpic_params *params,
125                                  struct file *file)
126 {
127         struct elf32_phdr *phdr;
128         unsigned long size;
129         int retval, loop;
130
131         if (params->hdr.e_phentsize != sizeof(struct elf_phdr))
132                 return -ENOMEM;
133         if (params->hdr.e_phnum > 65536U / sizeof(struct elf_phdr))
134                 return -ENOMEM;
135
136         size = params->hdr.e_phnum * sizeof(struct elf_phdr);
137         params->phdrs = kmalloc(size, GFP_KERNEL);
138         if (!params->phdrs)
139                 return -ENOMEM;
140
141         retval = kernel_read(file, params->hdr.e_phoff,
142                              (char *) params->phdrs, size);
143         if (unlikely(retval != size))
144                 return retval < 0 ? retval : -ENOEXEC;
145
146         /* determine stack size for this binary */
147         phdr = params->phdrs;
148         for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
149                 if (phdr->p_type != PT_GNU_STACK)
150                         continue;
151
152                 if (phdr->p_flags & PF_X)
153                         params->flags |= ELF_FDPIC_FLAG_EXEC_STACK;
154                 else
155                         params->flags |= ELF_FDPIC_FLAG_NOEXEC_STACK;
156
157                 params->stack_size = phdr->p_memsz;
158                 break;
159         }
160
161         return 0;
162 }
163
164 /*****************************************************************************/
165 /*
166  * load an fdpic binary into various bits of memory
167  */
168 static int load_elf_fdpic_binary(struct linux_binprm *bprm)
169 {
170         struct elf_fdpic_params exec_params, interp_params;
171         struct pt_regs *regs = current_pt_regs();
172         struct elf_phdr *phdr;
173         unsigned long stack_size, entryaddr;
174 #ifdef ELF_FDPIC_PLAT_INIT
175         unsigned long dynaddr;
176 #endif
177 #ifndef CONFIG_MMU
178         unsigned long stack_prot;
179 #endif
180         struct file *interpreter = NULL; /* to shut gcc up */
181         char *interpreter_name = NULL;
182         int executable_stack;
183         int retval, i;
184
185         kdebug("____ LOAD %d ____", current->pid);
186
187         memset(&exec_params, 0, sizeof(exec_params));
188         memset(&interp_params, 0, sizeof(interp_params));
189
190         exec_params.hdr = *(struct elfhdr *) bprm->buf;
191         exec_params.flags = ELF_FDPIC_FLAG_PRESENT | ELF_FDPIC_FLAG_EXECUTABLE;
192
193         /* check that this is a binary we know how to deal with */
194         retval = -ENOEXEC;
195         if (!is_elf_fdpic(&exec_params.hdr, bprm->file))
196                 goto error;
197
198         /* read the program header table */
199         retval = elf_fdpic_fetch_phdrs(&exec_params, bprm->file);
200         if (retval < 0)
201                 goto error;
202
203         /* scan for a program header that specifies an interpreter */
204         phdr = exec_params.phdrs;
205
206         for (i = 0; i < exec_params.hdr.e_phnum; i++, phdr++) {
207                 switch (phdr->p_type) {
208                 case PT_INTERP:
209                         retval = -ENOMEM;
210                         if (phdr->p_filesz > PATH_MAX)
211                                 goto error;
212                         retval = -ENOENT;
213                         if (phdr->p_filesz < 2)
214                                 goto error;
215
216                         /* read the name of the interpreter into memory */
217                         interpreter_name = kmalloc(phdr->p_filesz, GFP_KERNEL);
218                         if (!interpreter_name)
219                                 goto error;
220
221                         retval = kernel_read(bprm->file,
222                                              phdr->p_offset,
223                                              interpreter_name,
224                                              phdr->p_filesz);
225                         if (unlikely(retval != phdr->p_filesz)) {
226                                 if (retval >= 0)
227                                         retval = -ENOEXEC;
228                                 goto error;
229                         }
230
231                         retval = -ENOENT;
232                         if (interpreter_name[phdr->p_filesz - 1] != '\0')
233                                 goto error;
234
235                         kdebug("Using ELF interpreter %s", interpreter_name);
236
237                         /* replace the program with the interpreter */
238                         interpreter = open_exec(interpreter_name);
239                         retval = PTR_ERR(interpreter);
240                         if (IS_ERR(interpreter)) {
241                                 interpreter = NULL;
242                                 goto error;
243                         }
244
245                         /*
246                          * If the binary is not readable then enforce
247                          * mm->dumpable = 0 regardless of the interpreter's
248                          * permissions.
249                          */
250                         would_dump(bprm, interpreter);
251
252                         retval = kernel_read(interpreter, 0, bprm->buf,
253                                              BINPRM_BUF_SIZE);
254                         if (unlikely(retval != BINPRM_BUF_SIZE)) {
255                                 if (retval >= 0)
256                                         retval = -ENOEXEC;
257                                 goto error;
258                         }
259
260                         interp_params.hdr = *((struct elfhdr *) bprm->buf);
261                         break;
262
263                 case PT_LOAD:
264 #ifdef CONFIG_MMU
265                         if (exec_params.load_addr == 0)
266                                 exec_params.load_addr = phdr->p_vaddr;
267 #endif
268                         break;
269                 }
270
271         }
272
273         if (elf_check_const_displacement(&exec_params.hdr))
274                 exec_params.flags |= ELF_FDPIC_FLAG_CONSTDISP;
275
276         /* perform insanity checks on the interpreter */
277         if (interpreter_name) {
278                 retval = -ELIBBAD;
279                 if (!is_elf_fdpic(&interp_params.hdr, interpreter))
280                         goto error;
281
282                 interp_params.flags = ELF_FDPIC_FLAG_PRESENT;
283
284                 /* read the interpreter's program header table */
285                 retval = elf_fdpic_fetch_phdrs(&interp_params, interpreter);
286                 if (retval < 0)
287                         goto error;
288         }
289
290         stack_size = exec_params.stack_size;
291         if (exec_params.flags & ELF_FDPIC_FLAG_EXEC_STACK)
292                 executable_stack = EXSTACK_ENABLE_X;
293         else if (exec_params.flags & ELF_FDPIC_FLAG_NOEXEC_STACK)
294                 executable_stack = EXSTACK_DISABLE_X;
295         else
296                 executable_stack = EXSTACK_DEFAULT;
297
298         if (stack_size == 0) {
299                 stack_size = interp_params.stack_size;
300                 if (interp_params.flags & ELF_FDPIC_FLAG_EXEC_STACK)
301                         executable_stack = EXSTACK_ENABLE_X;
302                 else if (interp_params.flags & ELF_FDPIC_FLAG_NOEXEC_STACK)
303                         executable_stack = EXSTACK_DISABLE_X;
304                 else
305                         executable_stack = EXSTACK_DEFAULT;
306         }
307
308         retval = -ENOEXEC;
309         if (stack_size == 0)
310                 goto error;
311
312         if (elf_check_const_displacement(&interp_params.hdr))
313                 interp_params.flags |= ELF_FDPIC_FLAG_CONSTDISP;
314
315         /* flush all traces of the currently running executable */
316         retval = flush_old_exec(bprm);
317         if (retval)
318                 goto error;
319
320         /* there's now no turning back... the old userspace image is dead,
321          * defunct, deceased, etc.
322          */
323         set_personality(PER_LINUX_FDPIC);
324         if (elf_read_implies_exec(&exec_params.hdr, executable_stack))
325                 current->personality |= READ_IMPLIES_EXEC;
326
327         setup_new_exec(bprm);
328
329         set_binfmt(&elf_fdpic_format);
330
331         current->mm->start_code = 0;
332         current->mm->end_code = 0;
333         current->mm->start_stack = 0;
334         current->mm->start_data = 0;
335         current->mm->end_data = 0;
336         current->mm->context.exec_fdpic_loadmap = 0;
337         current->mm->context.interp_fdpic_loadmap = 0;
338
339 #ifdef CONFIG_MMU
340         elf_fdpic_arch_lay_out_mm(&exec_params,
341                                   &interp_params,
342                                   &current->mm->start_stack,
343                                   &current->mm->start_brk);
344
345         retval = setup_arg_pages(bprm, current->mm->start_stack,
346                                  executable_stack);
347         if (retval < 0)
348                 goto error;
349 #endif
350
351         /* load the executable and interpreter into memory */
352         retval = elf_fdpic_map_file(&exec_params, bprm->file, current->mm,
353                                     "executable");
354         if (retval < 0)
355                 goto error;
356
357         if (interpreter_name) {
358                 retval = elf_fdpic_map_file(&interp_params, interpreter,
359                                             current->mm, "interpreter");
360                 if (retval < 0) {
361                         printk(KERN_ERR "Unable to load interpreter\n");
362                         goto error;
363                 }
364
365                 allow_write_access(interpreter);
366                 fput(interpreter);
367                 interpreter = NULL;
368         }
369
370 #ifdef CONFIG_MMU
371         if (!current->mm->start_brk)
372                 current->mm->start_brk = current->mm->end_data;
373
374         current->mm->brk = current->mm->start_brk =
375                 PAGE_ALIGN(current->mm->start_brk);
376
377 #else
378         /* create a stack and brk area big enough for everyone
379          * - the brk heap starts at the bottom and works up
380          * - the stack starts at the top and works down
381          */
382         stack_size = (stack_size + PAGE_SIZE - 1) & PAGE_MASK;
383         if (stack_size < PAGE_SIZE * 2)
384                 stack_size = PAGE_SIZE * 2;
385
386         stack_prot = PROT_READ | PROT_WRITE;
387         if (executable_stack == EXSTACK_ENABLE_X ||
388             (executable_stack == EXSTACK_DEFAULT && VM_STACK_FLAGS & VM_EXEC))
389                 stack_prot |= PROT_EXEC;
390
391         current->mm->start_brk = vm_mmap(NULL, 0, stack_size, stack_prot,
392                                          MAP_PRIVATE | MAP_ANONYMOUS |
393                                          MAP_UNINITIALIZED | MAP_GROWSDOWN,
394                                          0);
395
396         if (IS_ERR_VALUE(current->mm->start_brk)) {
397                 retval = current->mm->start_brk;
398                 current->mm->start_brk = 0;
399                 goto error;
400         }
401
402         current->mm->brk = current->mm->start_brk;
403         current->mm->context.end_brk = current->mm->start_brk;
404         current->mm->context.end_brk +=
405                 (stack_size > PAGE_SIZE) ? (stack_size - PAGE_SIZE) : 0;
406         current->mm->start_stack = current->mm->start_brk + stack_size;
407 #endif
408
409         install_exec_creds(bprm);
410         if (create_elf_fdpic_tables(bprm, current->mm,
411                                     &exec_params, &interp_params) < 0)
412                 goto error;
413
414         kdebug("- start_code  %lx", current->mm->start_code);
415         kdebug("- end_code    %lx", current->mm->end_code);
416         kdebug("- start_data  %lx", current->mm->start_data);
417         kdebug("- end_data    %lx", current->mm->end_data);
418         kdebug("- start_brk   %lx", current->mm->start_brk);
419         kdebug("- brk         %lx", current->mm->brk);
420         kdebug("- start_stack %lx", current->mm->start_stack);
421
422 #ifdef ELF_FDPIC_PLAT_INIT
423         /*
424          * The ABI may specify that certain registers be set up in special
425          * ways (on i386 %edx is the address of a DT_FINI function, for
426          * example.  This macro performs whatever initialization to
427          * the regs structure is required.
428          */
429         dynaddr = interp_params.dynamic_addr ?: exec_params.dynamic_addr;
430         ELF_FDPIC_PLAT_INIT(regs, exec_params.map_addr, interp_params.map_addr,
431                             dynaddr);
432 #endif
433
434         /* everything is now ready... get the userspace context ready to roll */
435         entryaddr = interp_params.entry_addr ?: exec_params.entry_addr;
436         start_thread(regs, entryaddr, current->mm->start_stack);
437
438         retval = 0;
439
440 error:
441         if (interpreter) {
442                 allow_write_access(interpreter);
443                 fput(interpreter);
444         }
445         kfree(interpreter_name);
446         kfree(exec_params.phdrs);
447         kfree(exec_params.loadmap);
448         kfree(interp_params.phdrs);
449         kfree(interp_params.loadmap);
450         return retval;
451 }
452
453 /*****************************************************************************/
454
455 #ifndef ELF_BASE_PLATFORM
456 /*
457  * AT_BASE_PLATFORM indicates the "real" hardware/microarchitecture.
458  * If the arch defines ELF_BASE_PLATFORM (in asm/elf.h), the value
459  * will be copied to the user stack in the same manner as AT_PLATFORM.
460  */
461 #define ELF_BASE_PLATFORM NULL
462 #endif
463
464 /*
465  * present useful information to the program by shovelling it onto the new
466  * process's stack
467  */
468 static int create_elf_fdpic_tables(struct linux_binprm *bprm,
469                                    struct mm_struct *mm,
470                                    struct elf_fdpic_params *exec_params,
471                                    struct elf_fdpic_params *interp_params)
472 {
473         const struct cred *cred = current_cred();
474         unsigned long sp, csp, nitems;
475         elf_caddr_t __user *argv, *envp;
476         size_t platform_len = 0, len;
477         char *k_platform, *k_base_platform;
478         char __user *u_platform, *u_base_platform, *p;
479         int loop;
480         int nr; /* reset for each csp adjustment */
481
482 #ifdef CONFIG_MMU
483         /* In some cases (e.g. Hyper-Threading), we want to avoid L1 evictions
484          * by the processes running on the same package. One thing we can do is
485          * to shuffle the initial stack for them, so we give the architecture
486          * an opportunity to do so here.
487          */
488         sp = arch_align_stack(bprm->p);
489 #else
490         sp = mm->start_stack;
491
492         /* stack the program arguments and environment */
493         if (elf_fdpic_transfer_args_to_stack(bprm, &sp) < 0)
494                 return -EFAULT;
495 #endif
496
497         /*
498          * If this architecture has a platform capability string, copy it
499          * to userspace.  In some cases (Sparc), this info is impossible
500          * for userspace to get any other way, in others (i386) it is
501          * merely difficult.
502          */
503         k_platform = ELF_PLATFORM;
504         u_platform = NULL;
505
506         if (k_platform) {
507                 platform_len = strlen(k_platform) + 1;
508                 sp -= platform_len;
509                 u_platform = (char __user *) sp;
510                 if (__copy_to_user(u_platform, k_platform, platform_len) != 0)
511                         return -EFAULT;
512         }
513
514         /*
515          * If this architecture has a "base" platform capability
516          * string, copy it to userspace.
517          */
518         k_base_platform = ELF_BASE_PLATFORM;
519         u_base_platform = NULL;
520
521         if (k_base_platform) {
522                 platform_len = strlen(k_base_platform) + 1;
523                 sp -= platform_len;
524                 u_base_platform = (char __user *) sp;
525                 if (__copy_to_user(u_base_platform, k_base_platform, platform_len) != 0)
526                         return -EFAULT;
527         }
528
529         sp &= ~7UL;
530
531         /* stack the load map(s) */
532         len = sizeof(struct elf32_fdpic_loadmap);
533         len += sizeof(struct elf32_fdpic_loadseg) * exec_params->loadmap->nsegs;
534         sp = (sp - len) & ~7UL;
535         exec_params->map_addr = sp;
536
537         if (copy_to_user((void __user *) sp, exec_params->loadmap, len) != 0)
538                 return -EFAULT;
539
540         current->mm->context.exec_fdpic_loadmap = (unsigned long) sp;
541
542         if (interp_params->loadmap) {
543                 len = sizeof(struct elf32_fdpic_loadmap);
544                 len += sizeof(struct elf32_fdpic_loadseg) *
545                         interp_params->loadmap->nsegs;
546                 sp = (sp - len) & ~7UL;
547                 interp_params->map_addr = sp;
548
549                 if (copy_to_user((void __user *) sp, interp_params->loadmap,
550                                  len) != 0)
551                         return -EFAULT;
552
553                 current->mm->context.interp_fdpic_loadmap = (unsigned long) sp;
554         }
555
556         /* force 16 byte _final_ alignment here for generality */
557 #define DLINFO_ITEMS 15
558
559         nitems = 1 + DLINFO_ITEMS + (k_platform ? 1 : 0) +
560                 (k_base_platform ? 1 : 0) + AT_VECTOR_SIZE_ARCH;
561
562         if (bprm->interp_flags & BINPRM_FLAGS_EXECFD)
563                 nitems++;
564
565         csp = sp;
566         sp -= nitems * 2 * sizeof(unsigned long);
567         sp -= (bprm->envc + 1) * sizeof(char *);        /* envv[] */
568         sp -= (bprm->argc + 1) * sizeof(char *);        /* argv[] */
569         sp -= 1 * sizeof(unsigned long);                /* argc */
570
571         csp -= sp & 15UL;
572         sp -= sp & 15UL;
573
574         /* put the ELF interpreter info on the stack */
575 #define NEW_AUX_ENT(id, val)                                            \
576         do {                                                            \
577                 struct { unsigned long _id, _val; } __user *ent;        \
578                                                                         \
579                 ent = (void __user *) csp;                              \
580                 __put_user((id), &ent[nr]._id);                         \
581                 __put_user((val), &ent[nr]._val);                       \
582                 nr++;                                                   \
583         } while (0)
584
585         nr = 0;
586         csp -= 2 * sizeof(unsigned long);
587         NEW_AUX_ENT(AT_NULL, 0);
588         if (k_platform) {
589                 nr = 0;
590                 csp -= 2 * sizeof(unsigned long);
591                 NEW_AUX_ENT(AT_PLATFORM,
592                             (elf_addr_t) (unsigned long) u_platform);
593         }
594
595         if (k_base_platform) {
596                 nr = 0;
597                 csp -= 2 * sizeof(unsigned long);
598                 NEW_AUX_ENT(AT_BASE_PLATFORM,
599                             (elf_addr_t) (unsigned long) u_base_platform);
600         }
601
602         if (bprm->interp_flags & BINPRM_FLAGS_EXECFD) {
603                 nr = 0;
604                 csp -= 2 * sizeof(unsigned long);
605                 NEW_AUX_ENT(AT_EXECFD, bprm->interp_data);
606         }
607
608         nr = 0;
609         csp -= DLINFO_ITEMS * 2 * sizeof(unsigned long);
610         NEW_AUX_ENT(AT_HWCAP,   ELF_HWCAP);
611 #ifdef ELF_HWCAP2
612         NEW_AUX_ENT(AT_HWCAP2,  ELF_HWCAP2);
613 #endif
614         NEW_AUX_ENT(AT_PAGESZ,  PAGE_SIZE);
615         NEW_AUX_ENT(AT_CLKTCK,  CLOCKS_PER_SEC);
616         NEW_AUX_ENT(AT_PHDR,    exec_params->ph_addr);
617         NEW_AUX_ENT(AT_PHENT,   sizeof(struct elf_phdr));
618         NEW_AUX_ENT(AT_PHNUM,   exec_params->hdr.e_phnum);
619         NEW_AUX_ENT(AT_BASE,    interp_params->elfhdr_addr);
620         NEW_AUX_ENT(AT_FLAGS,   0);
621         NEW_AUX_ENT(AT_ENTRY,   exec_params->entry_addr);
622         NEW_AUX_ENT(AT_UID,     (elf_addr_t) from_kuid_munged(cred->user_ns, cred->uid));
623         NEW_AUX_ENT(AT_EUID,    (elf_addr_t) from_kuid_munged(cred->user_ns, cred->euid));
624         NEW_AUX_ENT(AT_GID,     (elf_addr_t) from_kgid_munged(cred->user_ns, cred->gid));
625         NEW_AUX_ENT(AT_EGID,    (elf_addr_t) from_kgid_munged(cred->user_ns, cred->egid));
626         NEW_AUX_ENT(AT_SECURE,  security_bprm_secureexec(bprm));
627         NEW_AUX_ENT(AT_EXECFN,  bprm->exec);
628
629 #ifdef ARCH_DLINFO
630         nr = 0;
631         csp -= AT_VECTOR_SIZE_ARCH * 2 * sizeof(unsigned long);
632
633         /* ARCH_DLINFO must come last so platform specific code can enforce
634          * special alignment requirements on the AUXV if necessary (eg. PPC).
635          */
636         ARCH_DLINFO;
637 #endif
638 #undef NEW_AUX_ENT
639
640         /* allocate room for argv[] and envv[] */
641         csp -= (bprm->envc + 1) * sizeof(elf_caddr_t);
642         envp = (elf_caddr_t __user *) csp;
643         csp -= (bprm->argc + 1) * sizeof(elf_caddr_t);
644         argv = (elf_caddr_t __user *) csp;
645
646         /* stack argc */
647         csp -= sizeof(unsigned long);
648         __put_user(bprm->argc, (unsigned long __user *) csp);
649
650         BUG_ON(csp != sp);
651
652         /* fill in the argv[] array */
653 #ifdef CONFIG_MMU
654         current->mm->arg_start = bprm->p;
655 #else
656         current->mm->arg_start = current->mm->start_stack -
657                 (MAX_ARG_PAGES * PAGE_SIZE - bprm->p);
658 #endif
659
660         p = (char __user *) current->mm->arg_start;
661         for (loop = bprm->argc; loop > 0; loop--) {
662                 __put_user((elf_caddr_t) p, argv++);
663                 len = strnlen_user(p, MAX_ARG_STRLEN);
664                 if (!len || len > MAX_ARG_STRLEN)
665                         return -EINVAL;
666                 p += len;
667         }
668         __put_user(NULL, argv);
669         current->mm->arg_end = (unsigned long) p;
670
671         /* fill in the envv[] array */
672         current->mm->env_start = (unsigned long) p;
673         for (loop = bprm->envc; loop > 0; loop--) {
674                 __put_user((elf_caddr_t)(unsigned long) p, envp++);
675                 len = strnlen_user(p, MAX_ARG_STRLEN);
676                 if (!len || len > MAX_ARG_STRLEN)
677                         return -EINVAL;
678                 p += len;
679         }
680         __put_user(NULL, envp);
681         current->mm->env_end = (unsigned long) p;
682
683         mm->start_stack = (unsigned long) sp;
684         return 0;
685 }
686
687 /*****************************************************************************/
688 /*
689  * transfer the program arguments and environment from the holding pages onto
690  * the stack
691  */
692 #ifndef CONFIG_MMU
693 static int elf_fdpic_transfer_args_to_stack(struct linux_binprm *bprm,
694                                             unsigned long *_sp)
695 {
696         unsigned long index, stop, sp;
697         char *src;
698         int ret = 0;
699
700         stop = bprm->p >> PAGE_SHIFT;
701         sp = *_sp;
702
703         for (index = MAX_ARG_PAGES - 1; index >= stop; index--) {
704                 src = kmap(bprm->page[index]);
705                 sp -= PAGE_SIZE;
706                 if (copy_to_user((void *) sp, src, PAGE_SIZE) != 0)
707                         ret = -EFAULT;
708                 kunmap(bprm->page[index]);
709                 if (ret < 0)
710                         goto out;
711         }
712
713         *_sp = (*_sp - (MAX_ARG_PAGES * PAGE_SIZE - bprm->p)) & ~15;
714
715 out:
716         return ret;
717 }
718 #endif
719
720 /*****************************************************************************/
721 /*
722  * load the appropriate binary image (executable or interpreter) into memory
723  * - we assume no MMU is available
724  * - if no other PIC bits are set in params->hdr->e_flags
725  *   - we assume that the LOADable segments in the binary are independently relocatable
726  *   - we assume R/O executable segments are shareable
727  * - else
728  *   - we assume the loadable parts of the image to require fixed displacement
729  *   - the image is not shareable
730  */
731 static int elf_fdpic_map_file(struct elf_fdpic_params *params,
732                               struct file *file,
733                               struct mm_struct *mm,
734                               const char *what)
735 {
736         struct elf32_fdpic_loadmap *loadmap;
737 #ifdef CONFIG_MMU
738         struct elf32_fdpic_loadseg *mseg;
739 #endif
740         struct elf32_fdpic_loadseg *seg;
741         struct elf32_phdr *phdr;
742         unsigned long load_addr, stop;
743         unsigned nloads, tmp;
744         size_t size;
745         int loop, ret;
746
747         /* allocate a load map table */
748         nloads = 0;
749         for (loop = 0; loop < params->hdr.e_phnum; loop++)
750                 if (params->phdrs[loop].p_type == PT_LOAD)
751                         nloads++;
752
753         if (nloads == 0)
754                 return -ELIBBAD;
755
756         size = sizeof(*loadmap) + nloads * sizeof(*seg);
757         loadmap = kzalloc(size, GFP_KERNEL);
758         if (!loadmap)
759                 return -ENOMEM;
760
761         params->loadmap = loadmap;
762
763         loadmap->version = ELF32_FDPIC_LOADMAP_VERSION;
764         loadmap->nsegs = nloads;
765
766         load_addr = params->load_addr;
767         seg = loadmap->segs;
768
769         /* map the requested LOADs into the memory space */
770         switch (params->flags & ELF_FDPIC_FLAG_ARRANGEMENT) {
771         case ELF_FDPIC_FLAG_CONSTDISP:
772         case ELF_FDPIC_FLAG_CONTIGUOUS:
773 #ifndef CONFIG_MMU
774                 ret = elf_fdpic_map_file_constdisp_on_uclinux(params, file, mm);
775                 if (ret < 0)
776                         return ret;
777                 break;
778 #endif
779         default:
780                 ret = elf_fdpic_map_file_by_direct_mmap(params, file, mm);
781                 if (ret < 0)
782                         return ret;
783                 break;
784         }
785
786         /* map the entry point */
787         if (params->hdr.e_entry) {
788                 seg = loadmap->segs;
789                 for (loop = loadmap->nsegs; loop > 0; loop--, seg++) {
790                         if (params->hdr.e_entry >= seg->p_vaddr &&
791                             params->hdr.e_entry < seg->p_vaddr + seg->p_memsz) {
792                                 params->entry_addr =
793                                         (params->hdr.e_entry - seg->p_vaddr) +
794                                         seg->addr;
795                                 break;
796                         }
797                 }
798         }
799
800         /* determine where the program header table has wound up if mapped */
801         stop = params->hdr.e_phoff;
802         stop += params->hdr.e_phnum * sizeof (struct elf_phdr);
803         phdr = params->phdrs;
804
805         for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
806                 if (phdr->p_type != PT_LOAD)
807                         continue;
808
809                 if (phdr->p_offset > params->hdr.e_phoff ||
810                     phdr->p_offset + phdr->p_filesz < stop)
811                         continue;
812
813                 seg = loadmap->segs;
814                 for (loop = loadmap->nsegs; loop > 0; loop--, seg++) {
815                         if (phdr->p_vaddr >= seg->p_vaddr &&
816                             phdr->p_vaddr + phdr->p_filesz <=
817                             seg->p_vaddr + seg->p_memsz) {
818                                 params->ph_addr =
819                                         (phdr->p_vaddr - seg->p_vaddr) +
820                                         seg->addr +
821                                         params->hdr.e_phoff - phdr->p_offset;
822                                 break;
823                         }
824                 }
825                 break;
826         }
827
828         /* determine where the dynamic section has wound up if there is one */
829         phdr = params->phdrs;
830         for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
831                 if (phdr->p_type != PT_DYNAMIC)
832                         continue;
833
834                 seg = loadmap->segs;
835                 for (loop = loadmap->nsegs; loop > 0; loop--, seg++) {
836                         if (phdr->p_vaddr >= seg->p_vaddr &&
837                             phdr->p_vaddr + phdr->p_memsz <=
838                             seg->p_vaddr + seg->p_memsz) {
839                                 params->dynamic_addr =
840                                         (phdr->p_vaddr - seg->p_vaddr) +
841                                         seg->addr;
842
843                                 /* check the dynamic section contains at least
844                                  * one item, and that the last item is a NULL
845                                  * entry */
846                                 if (phdr->p_memsz == 0 ||
847                                     phdr->p_memsz % sizeof(Elf32_Dyn) != 0)
848                                         goto dynamic_error;
849
850                                 tmp = phdr->p_memsz / sizeof(Elf32_Dyn);
851                                 if (((Elf32_Dyn *)
852                                      params->dynamic_addr)[tmp - 1].d_tag != 0)
853                                         goto dynamic_error;
854                                 break;
855                         }
856                 }
857                 break;
858         }
859
860         /* now elide adjacent segments in the load map on MMU linux
861          * - on uClinux the holes between may actually be filled with system
862          *   stuff or stuff from other processes
863          */
864 #ifdef CONFIG_MMU
865         nloads = loadmap->nsegs;
866         mseg = loadmap->segs;
867         seg = mseg + 1;
868         for (loop = 1; loop < nloads; loop++) {
869                 /* see if we have a candidate for merging */
870                 if (seg->p_vaddr - mseg->p_vaddr == seg->addr - mseg->addr) {
871                         load_addr = PAGE_ALIGN(mseg->addr + mseg->p_memsz);
872                         if (load_addr == (seg->addr & PAGE_MASK)) {
873                                 mseg->p_memsz +=
874                                         load_addr -
875                                         (mseg->addr + mseg->p_memsz);
876                                 mseg->p_memsz += seg->addr & ~PAGE_MASK;
877                                 mseg->p_memsz += seg->p_memsz;
878                                 loadmap->nsegs--;
879                                 continue;
880                         }
881                 }
882
883                 mseg++;
884                 if (mseg != seg)
885                         *mseg = *seg;
886         }
887 #endif
888
889         kdebug("Mapped Object [%s]:", what);
890         kdebug("- elfhdr   : %lx", params->elfhdr_addr);
891         kdebug("- entry    : %lx", params->entry_addr);
892         kdebug("- PHDR[]   : %lx", params->ph_addr);
893         kdebug("- DYNAMIC[]: %lx", params->dynamic_addr);
894         seg = loadmap->segs;
895         for (loop = 0; loop < loadmap->nsegs; loop++, seg++)
896                 kdebug("- LOAD[%d] : %08x-%08x [va=%x ms=%x]",
897                        loop,
898                        seg->addr, seg->addr + seg->p_memsz - 1,
899                        seg->p_vaddr, seg->p_memsz);
900
901         return 0;
902
903 dynamic_error:
904         printk("ELF FDPIC %s with invalid DYNAMIC section (inode=%lu)\n",
905                what, file_inode(file)->i_ino);
906         return -ELIBBAD;
907 }
908
909 /*****************************************************************************/
910 /*
911  * map a file with constant displacement under uClinux
912  */
913 #ifndef CONFIG_MMU
914 static int elf_fdpic_map_file_constdisp_on_uclinux(
915         struct elf_fdpic_params *params,
916         struct file *file,
917         struct mm_struct *mm)
918 {
919         struct elf32_fdpic_loadseg *seg;
920         struct elf32_phdr *phdr;
921         unsigned long load_addr, base = ULONG_MAX, top = 0, maddr = 0, mflags;
922         int loop, ret;
923
924         load_addr = params->load_addr;
925         seg = params->loadmap->segs;
926
927         /* determine the bounds of the contiguous overall allocation we must
928          * make */
929         phdr = params->phdrs;
930         for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
931                 if (params->phdrs[loop].p_type != PT_LOAD)
932                         continue;
933
934                 if (base > phdr->p_vaddr)
935                         base = phdr->p_vaddr;
936                 if (top < phdr->p_vaddr + phdr->p_memsz)
937                         top = phdr->p_vaddr + phdr->p_memsz;
938         }
939
940         /* allocate one big anon block for everything */
941         mflags = MAP_PRIVATE;
942         if (params->flags & ELF_FDPIC_FLAG_EXECUTABLE)
943                 mflags |= MAP_EXECUTABLE;
944
945         maddr = vm_mmap(NULL, load_addr, top - base,
946                         PROT_READ | PROT_WRITE | PROT_EXEC, mflags, 0);
947         if (IS_ERR_VALUE(maddr))
948                 return (int) maddr;
949
950         if (load_addr != 0)
951                 load_addr += PAGE_ALIGN(top - base);
952
953         /* and then load the file segments into it */
954         phdr = params->phdrs;
955         for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
956                 if (params->phdrs[loop].p_type != PT_LOAD)
957                         continue;
958
959                 seg->addr = maddr + (phdr->p_vaddr - base);
960                 seg->p_vaddr = phdr->p_vaddr;
961                 seg->p_memsz = phdr->p_memsz;
962
963                 ret = read_code(file, seg->addr, phdr->p_offset,
964                                        phdr->p_filesz);
965                 if (ret < 0)
966                         return ret;
967
968                 /* map the ELF header address if in this segment */
969                 if (phdr->p_offset == 0)
970                         params->elfhdr_addr = seg->addr;
971
972                 /* clear any space allocated but not loaded */
973                 if (phdr->p_filesz < phdr->p_memsz) {
974                         if (clear_user((void *) (seg->addr + phdr->p_filesz),
975                                        phdr->p_memsz - phdr->p_filesz))
976                                 return -EFAULT;
977                 }
978
979                 if (mm) {
980                         if (phdr->p_flags & PF_X) {
981                                 if (!mm->start_code) {
982                                         mm->start_code = seg->addr;
983                                         mm->end_code = seg->addr +
984                                                 phdr->p_memsz;
985                                 }
986                         } else if (!mm->start_data) {
987                                 mm->start_data = seg->addr;
988                                 mm->end_data = seg->addr + phdr->p_memsz;
989                         }
990                 }
991
992                 seg++;
993         }
994
995         return 0;
996 }
997 #endif
998
999 /*****************************************************************************/
1000 /*
1001  * map a binary by direct mmap() of the individual PT_LOAD segments
1002  */
1003 static int elf_fdpic_map_file_by_direct_mmap(struct elf_fdpic_params *params,
1004                                              struct file *file,
1005                                              struct mm_struct *mm)
1006 {
1007         struct elf32_fdpic_loadseg *seg;
1008         struct elf32_phdr *phdr;
1009         unsigned long load_addr, delta_vaddr;
1010         int loop, dvset;
1011
1012         load_addr = params->load_addr;
1013         delta_vaddr = 0;
1014         dvset = 0;
1015
1016         seg = params->loadmap->segs;
1017
1018         /* deal with each load segment separately */
1019         phdr = params->phdrs;
1020         for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
1021                 unsigned long maddr, disp, excess, excess1;
1022                 int prot = 0, flags;
1023
1024                 if (phdr->p_type != PT_LOAD)
1025                         continue;
1026
1027                 kdebug("[LOAD] va=%lx of=%lx fs=%lx ms=%lx",
1028                        (unsigned long) phdr->p_vaddr,
1029                        (unsigned long) phdr->p_offset,
1030                        (unsigned long) phdr->p_filesz,
1031                        (unsigned long) phdr->p_memsz);
1032
1033                 /* determine the mapping parameters */
1034                 if (phdr->p_flags & PF_R) prot |= PROT_READ;
1035                 if (phdr->p_flags & PF_W) prot |= PROT_WRITE;
1036                 if (phdr->p_flags & PF_X) prot |= PROT_EXEC;
1037
1038                 flags = MAP_PRIVATE | MAP_DENYWRITE;
1039                 if (params->flags & ELF_FDPIC_FLAG_EXECUTABLE)
1040                         flags |= MAP_EXECUTABLE;
1041
1042                 maddr = 0;
1043
1044                 switch (params->flags & ELF_FDPIC_FLAG_ARRANGEMENT) {
1045                 case ELF_FDPIC_FLAG_INDEPENDENT:
1046                         /* PT_LOADs are independently locatable */
1047                         break;
1048
1049                 case ELF_FDPIC_FLAG_HONOURVADDR:
1050                         /* the specified virtual address must be honoured */
1051                         maddr = phdr->p_vaddr;
1052                         flags |= MAP_FIXED;
1053                         break;
1054
1055                 case ELF_FDPIC_FLAG_CONSTDISP:
1056                         /* constant displacement
1057                          * - can be mapped anywhere, but must be mapped as a
1058                          *   unit
1059                          */
1060                         if (!dvset) {
1061                                 maddr = load_addr;
1062                                 delta_vaddr = phdr->p_vaddr;
1063                                 dvset = 1;
1064                         } else {
1065                                 maddr = load_addr + phdr->p_vaddr - delta_vaddr;
1066                                 flags |= MAP_FIXED;
1067                         }
1068                         break;
1069
1070                 case ELF_FDPIC_FLAG_CONTIGUOUS:
1071                         /* contiguity handled later */
1072                         break;
1073
1074                 default:
1075                         BUG();
1076                 }
1077
1078                 maddr &= PAGE_MASK;
1079
1080                 /* create the mapping */
1081                 disp = phdr->p_vaddr & ~PAGE_MASK;
1082                 maddr = vm_mmap(file, maddr, phdr->p_memsz + disp, prot, flags,
1083                                 phdr->p_offset - disp);
1084
1085                 kdebug("mmap[%d] <file> sz=%lx pr=%x fl=%x of=%lx --> %08lx",
1086                        loop, phdr->p_memsz + disp, prot, flags,
1087                        phdr->p_offset - disp, maddr);
1088
1089                 if (IS_ERR_VALUE(maddr))
1090                         return (int) maddr;
1091
1092                 if ((params->flags & ELF_FDPIC_FLAG_ARRANGEMENT) ==
1093                     ELF_FDPIC_FLAG_CONTIGUOUS)
1094                         load_addr += PAGE_ALIGN(phdr->p_memsz + disp);
1095
1096                 seg->addr = maddr + disp;
1097                 seg->p_vaddr = phdr->p_vaddr;
1098                 seg->p_memsz = phdr->p_memsz;
1099
1100                 /* map the ELF header address if in this segment */
1101                 if (phdr->p_offset == 0)
1102                         params->elfhdr_addr = seg->addr;
1103
1104                 /* clear the bit between beginning of mapping and beginning of
1105                  * PT_LOAD */
1106                 if (prot & PROT_WRITE && disp > 0) {
1107                         kdebug("clear[%d] ad=%lx sz=%lx", loop, maddr, disp);
1108                         if (clear_user((void __user *) maddr, disp))
1109                                 return -EFAULT;
1110                         maddr += disp;
1111                 }
1112
1113                 /* clear any space allocated but not loaded
1114                  * - on uClinux we can just clear the lot
1115                  * - on MMU linux we'll get a SIGBUS beyond the last page
1116                  *   extant in the file
1117                  */
1118                 excess = phdr->p_memsz - phdr->p_filesz;
1119                 excess1 = PAGE_SIZE - ((maddr + phdr->p_filesz) & ~PAGE_MASK);
1120
1121 #ifdef CONFIG_MMU
1122                 if (excess > excess1) {
1123                         unsigned long xaddr = maddr + phdr->p_filesz + excess1;
1124                         unsigned long xmaddr;
1125
1126                         flags |= MAP_FIXED | MAP_ANONYMOUS;
1127                         xmaddr = vm_mmap(NULL, xaddr, excess - excess1,
1128                                          prot, flags, 0);
1129
1130                         kdebug("mmap[%d] <anon>"
1131                                " ad=%lx sz=%lx pr=%x fl=%x of=0 --> %08lx",
1132                                loop, xaddr, excess - excess1, prot, flags,
1133                                xmaddr);
1134
1135                         if (xmaddr != xaddr)
1136                                 return -ENOMEM;
1137                 }
1138
1139                 if (prot & PROT_WRITE && excess1 > 0) {
1140                         kdebug("clear[%d] ad=%lx sz=%lx",
1141                                loop, maddr + phdr->p_filesz, excess1);
1142                         if (clear_user((void __user *) maddr + phdr->p_filesz,
1143                                        excess1))
1144                                 return -EFAULT;
1145                 }
1146
1147 #else
1148                 if (excess > 0) {
1149                         kdebug("clear[%d] ad=%lx sz=%lx",
1150                                loop, maddr + phdr->p_filesz, excess);
1151                         if (clear_user((void *) maddr + phdr->p_filesz, excess))
1152                                 return -EFAULT;
1153                 }
1154 #endif
1155
1156                 if (mm) {
1157                         if (phdr->p_flags & PF_X) {
1158                                 if (!mm->start_code) {
1159                                         mm->start_code = maddr;
1160                                         mm->end_code = maddr + phdr->p_memsz;
1161                                 }
1162                         } else if (!mm->start_data) {
1163                                 mm->start_data = maddr;
1164                                 mm->end_data = maddr + phdr->p_memsz;
1165                         }
1166                 }
1167
1168                 seg++;
1169         }
1170
1171         return 0;
1172 }
1173
1174 /*****************************************************************************/
1175 /*
1176  * ELF-FDPIC core dumper
1177  *
1178  * Modelled on fs/exec.c:aout_core_dump()
1179  * Jeremy Fitzhardinge <jeremy@sw.oz.au>
1180  *
1181  * Modelled on fs/binfmt_elf.c core dumper
1182  */
1183 #ifdef CONFIG_ELF_CORE
1184
1185 /*
1186  * Decide whether a segment is worth dumping; default is yes to be
1187  * sure (missing info is worse than too much; etc).
1188  * Personally I'd include everything, and use the coredump limit...
1189  *
1190  * I think we should skip something. But I am not sure how. H.J.
1191  */
1192 static int maydump(struct vm_area_struct *vma, unsigned long mm_flags)
1193 {
1194         int dump_ok;
1195
1196         /* Do not dump I/O mapped devices or special mappings */
1197         if (vma->vm_flags & VM_IO) {
1198                 kdcore("%08lx: %08lx: no (IO)", vma->vm_start, vma->vm_flags);
1199                 return 0;
1200         }
1201
1202         /* If we may not read the contents, don't allow us to dump
1203          * them either. "dump_write()" can't handle it anyway.
1204          */
1205         if (!(vma->vm_flags & VM_READ)) {
1206                 kdcore("%08lx: %08lx: no (!read)", vma->vm_start, vma->vm_flags);
1207                 return 0;
1208         }
1209
1210         /* support for DAX */
1211         if (vma_is_dax(vma)) {
1212                 if (vma->vm_flags & VM_SHARED) {
1213                         dump_ok = test_bit(MMF_DUMP_DAX_SHARED, &mm_flags);
1214                         kdcore("%08lx: %08lx: %s (DAX shared)", vma->vm_start,
1215                                vma->vm_flags, dump_ok ? "yes" : "no");
1216                 } else {
1217                         dump_ok = test_bit(MMF_DUMP_DAX_PRIVATE, &mm_flags);
1218                         kdcore("%08lx: %08lx: %s (DAX private)", vma->vm_start,
1219                                vma->vm_flags, dump_ok ? "yes" : "no");
1220                 }
1221                 return dump_ok;
1222         }
1223
1224         /* By default, dump shared memory if mapped from an anonymous file. */
1225         if (vma->vm_flags & VM_SHARED) {
1226                 if (file_inode(vma->vm_file)->i_nlink == 0) {
1227                         dump_ok = test_bit(MMF_DUMP_ANON_SHARED, &mm_flags);
1228                         kdcore("%08lx: %08lx: %s (share)", vma->vm_start,
1229                                vma->vm_flags, dump_ok ? "yes" : "no");
1230                         return dump_ok;
1231                 }
1232
1233                 dump_ok = test_bit(MMF_DUMP_MAPPED_SHARED, &mm_flags);
1234                 kdcore("%08lx: %08lx: %s (share)", vma->vm_start,
1235                        vma->vm_flags, dump_ok ? "yes" : "no");
1236                 return dump_ok;
1237         }
1238
1239 #ifdef CONFIG_MMU
1240         /* By default, if it hasn't been written to, don't write it out */
1241         if (!vma->anon_vma) {
1242                 dump_ok = test_bit(MMF_DUMP_MAPPED_PRIVATE, &mm_flags);
1243                 kdcore("%08lx: %08lx: %s (!anon)", vma->vm_start,
1244                        vma->vm_flags, dump_ok ? "yes" : "no");
1245                 return dump_ok;
1246         }
1247 #endif
1248
1249         dump_ok = test_bit(MMF_DUMP_ANON_PRIVATE, &mm_flags);
1250         kdcore("%08lx: %08lx: %s", vma->vm_start, vma->vm_flags,
1251                dump_ok ? "yes" : "no");
1252         return dump_ok;
1253 }
1254
1255 /* An ELF note in memory */
1256 struct memelfnote
1257 {
1258         const char *name;
1259         int type;
1260         unsigned int datasz;
1261         void *data;
1262 };
1263
1264 static int notesize(struct memelfnote *en)
1265 {
1266         int sz;
1267
1268         sz = sizeof(struct elf_note);
1269         sz += roundup(strlen(en->name) + 1, 4);
1270         sz += roundup(en->datasz, 4);
1271
1272         return sz;
1273 }
1274
1275 /* #define DEBUG */
1276
1277 static int writenote(struct memelfnote *men, struct coredump_params *cprm)
1278 {
1279         struct elf_note en;
1280         en.n_namesz = strlen(men->name) + 1;
1281         en.n_descsz = men->datasz;
1282         en.n_type = men->type;
1283
1284         return dump_emit(cprm, &en, sizeof(en)) &&
1285                 dump_emit(cprm, men->name, en.n_namesz) && dump_align(cprm, 4) &&
1286                 dump_emit(cprm, men->data, men->datasz) && dump_align(cprm, 4);
1287 }
1288
1289 static inline void fill_elf_fdpic_header(struct elfhdr *elf, int segs)
1290 {
1291         memcpy(elf->e_ident, ELFMAG, SELFMAG);
1292         elf->e_ident[EI_CLASS] = ELF_CLASS;
1293         elf->e_ident[EI_DATA] = ELF_DATA;
1294         elf->e_ident[EI_VERSION] = EV_CURRENT;
1295         elf->e_ident[EI_OSABI] = ELF_OSABI;
1296         memset(elf->e_ident+EI_PAD, 0, EI_NIDENT-EI_PAD);
1297
1298         elf->e_type = ET_CORE;
1299         elf->e_machine = ELF_ARCH;
1300         elf->e_version = EV_CURRENT;
1301         elf->e_entry = 0;
1302         elf->e_phoff = sizeof(struct elfhdr);
1303         elf->e_shoff = 0;
1304         elf->e_flags = ELF_FDPIC_CORE_EFLAGS;
1305         elf->e_ehsize = sizeof(struct elfhdr);
1306         elf->e_phentsize = sizeof(struct elf_phdr);
1307         elf->e_phnum = segs;
1308         elf->e_shentsize = 0;
1309         elf->e_shnum = 0;
1310         elf->e_shstrndx = 0;
1311         return;
1312 }
1313
1314 static inline void fill_elf_note_phdr(struct elf_phdr *phdr, int sz, loff_t offset)
1315 {
1316         phdr->p_type = PT_NOTE;
1317         phdr->p_offset = offset;
1318         phdr->p_vaddr = 0;
1319         phdr->p_paddr = 0;
1320         phdr->p_filesz = sz;
1321         phdr->p_memsz = 0;
1322         phdr->p_flags = 0;
1323         phdr->p_align = 0;
1324         return;
1325 }
1326
1327 static inline void fill_note(struct memelfnote *note, const char *name, int type,
1328                 unsigned int sz, void *data)
1329 {
1330         note->name = name;
1331         note->type = type;
1332         note->datasz = sz;
1333         note->data = data;
1334         return;
1335 }
1336
1337 /*
1338  * fill up all the fields in prstatus from the given task struct, except
1339  * registers which need to be filled up separately.
1340  */
1341 static void fill_prstatus(struct elf_prstatus *prstatus,
1342                           struct task_struct *p, long signr)
1343 {
1344         prstatus->pr_info.si_signo = prstatus->pr_cursig = signr;
1345         prstatus->pr_sigpend = p->pending.signal.sig[0];
1346         prstatus->pr_sighold = p->blocked.sig[0];
1347         rcu_read_lock();
1348         prstatus->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
1349         rcu_read_unlock();
1350         prstatus->pr_pid = task_pid_vnr(p);
1351         prstatus->pr_pgrp = task_pgrp_vnr(p);
1352         prstatus->pr_sid = task_session_vnr(p);
1353         if (thread_group_leader(p)) {
1354                 struct task_cputime cputime;
1355
1356                 /*
1357                  * This is the record for the group leader.  It shows the
1358                  * group-wide total, not its individual thread total.
1359                  */
1360                 thread_group_cputime(p, &cputime);
1361                 cputime_to_timeval(cputime.utime, &prstatus->pr_utime);
1362                 cputime_to_timeval(cputime.stime, &prstatus->pr_stime);
1363         } else {
1364                 cputime_t utime, stime;
1365
1366                 task_cputime(p, &utime, &stime);
1367                 cputime_to_timeval(utime, &prstatus->pr_utime);
1368                 cputime_to_timeval(stime, &prstatus->pr_stime);
1369         }
1370         cputime_to_timeval(p->signal->cutime, &prstatus->pr_cutime);
1371         cputime_to_timeval(p->signal->cstime, &prstatus->pr_cstime);
1372
1373         prstatus->pr_exec_fdpic_loadmap = p->mm->context.exec_fdpic_loadmap;
1374         prstatus->pr_interp_fdpic_loadmap = p->mm->context.interp_fdpic_loadmap;
1375 }
1376
1377 static int fill_psinfo(struct elf_prpsinfo *psinfo, struct task_struct *p,
1378                        struct mm_struct *mm)
1379 {
1380         const struct cred *cred;
1381         unsigned int i, len;
1382
1383         /* first copy the parameters from user space */
1384         memset(psinfo, 0, sizeof(struct elf_prpsinfo));
1385
1386         len = mm->arg_end - mm->arg_start;
1387         if (len >= ELF_PRARGSZ)
1388                 len = ELF_PRARGSZ - 1;
1389         if (copy_from_user(&psinfo->pr_psargs,
1390                            (const char __user *) mm->arg_start, len))
1391                 return -EFAULT;
1392         for (i = 0; i < len; i++)
1393                 if (psinfo->pr_psargs[i] == 0)
1394                         psinfo->pr_psargs[i] = ' ';
1395         psinfo->pr_psargs[len] = 0;
1396
1397         rcu_read_lock();
1398         psinfo->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
1399         rcu_read_unlock();
1400         psinfo->pr_pid = task_pid_vnr(p);
1401         psinfo->pr_pgrp = task_pgrp_vnr(p);
1402         psinfo->pr_sid = task_session_vnr(p);
1403
1404         i = p->state ? ffz(~p->state) + 1 : 0;
1405         psinfo->pr_state = i;
1406         psinfo->pr_sname = (i > 5) ? '.' : "RSDTZW"[i];
1407         psinfo->pr_zomb = psinfo->pr_sname == 'Z';
1408         psinfo->pr_nice = task_nice(p);
1409         psinfo->pr_flag = p->flags;
1410         rcu_read_lock();
1411         cred = __task_cred(p);
1412         SET_UID(psinfo->pr_uid, from_kuid_munged(cred->user_ns, cred->uid));
1413         SET_GID(psinfo->pr_gid, from_kgid_munged(cred->user_ns, cred->gid));
1414         rcu_read_unlock();
1415         strncpy(psinfo->pr_fname, p->comm, sizeof(psinfo->pr_fname));
1416
1417         return 0;
1418 }
1419
1420 /* Here is the structure in which status of each thread is captured. */
1421 struct elf_thread_status
1422 {
1423         struct list_head list;
1424         struct elf_prstatus prstatus;   /* NT_PRSTATUS */
1425         elf_fpregset_t fpu;             /* NT_PRFPREG */
1426         struct task_struct *thread;
1427 #ifdef ELF_CORE_COPY_XFPREGS
1428         elf_fpxregset_t xfpu;           /* ELF_CORE_XFPREG_TYPE */
1429 #endif
1430         struct memelfnote notes[3];
1431         int num_notes;
1432 };
1433
1434 /*
1435  * In order to add the specific thread information for the elf file format,
1436  * we need to keep a linked list of every thread's pr_status and then create
1437  * a single section for them in the final core file.
1438  */
1439 static int elf_dump_thread_status(long signr, struct elf_thread_status *t)
1440 {
1441         struct task_struct *p = t->thread;
1442         int sz = 0;
1443
1444         t->num_notes = 0;
1445
1446         fill_prstatus(&t->prstatus, p, signr);
1447         elf_core_copy_task_regs(p, &t->prstatus.pr_reg);
1448
1449         fill_note(&t->notes[0], "CORE", NT_PRSTATUS, sizeof(t->prstatus),
1450                   &t->prstatus);
1451         t->num_notes++;
1452         sz += notesize(&t->notes[0]);
1453
1454         t->prstatus.pr_fpvalid = elf_core_copy_task_fpregs(p, NULL, &t->fpu);
1455         if (t->prstatus.pr_fpvalid) {
1456                 fill_note(&t->notes[1], "CORE", NT_PRFPREG, sizeof(t->fpu),
1457                           &t->fpu);
1458                 t->num_notes++;
1459                 sz += notesize(&t->notes[1]);
1460         }
1461
1462 #ifdef ELF_CORE_COPY_XFPREGS
1463         if (elf_core_copy_task_xfpregs(p, &t->xfpu)) {
1464                 fill_note(&t->notes[2], "LINUX", ELF_CORE_XFPREG_TYPE,
1465                           sizeof(t->xfpu), &t->xfpu);
1466                 t->num_notes++;
1467                 sz += notesize(&t->notes[2]);
1468         }
1469 #endif
1470         return sz;
1471 }
1472
1473 static void fill_extnum_info(struct elfhdr *elf, struct elf_shdr *shdr4extnum,
1474                              elf_addr_t e_shoff, int segs)
1475 {
1476         elf->e_shoff = e_shoff;
1477         elf->e_shentsize = sizeof(*shdr4extnum);
1478         elf->e_shnum = 1;
1479         elf->e_shstrndx = SHN_UNDEF;
1480
1481         memset(shdr4extnum, 0, sizeof(*shdr4extnum));
1482
1483         shdr4extnum->sh_type = SHT_NULL;
1484         shdr4extnum->sh_size = elf->e_shnum;
1485         shdr4extnum->sh_link = elf->e_shstrndx;
1486         shdr4extnum->sh_info = segs;
1487 }
1488
1489 /*
1490  * dump the segments for an MMU process
1491  */
1492 static bool elf_fdpic_dump_segments(struct coredump_params *cprm)
1493 {
1494         struct vm_area_struct *vma;
1495
1496         for (vma = current->mm->mmap; vma; vma = vma->vm_next) {
1497                 unsigned long addr;
1498
1499                 if (!maydump(vma, cprm->mm_flags))
1500                         continue;
1501
1502 #ifdef CONFIG_MMU
1503                 for (addr = vma->vm_start; addr < vma->vm_end;
1504                                                         addr += PAGE_SIZE) {
1505                         bool res;
1506                         struct page *page = get_dump_page(addr);
1507                         if (page) {
1508                                 void *kaddr = kmap(page);
1509                                 res = dump_emit(cprm, kaddr, PAGE_SIZE);
1510                                 kunmap(page);
1511                                 page_cache_release(page);
1512                         } else {
1513                                 res = dump_skip(cprm, PAGE_SIZE);
1514                         }
1515                         if (!res)
1516                                 return false;
1517                 }
1518 #else
1519                 if (!dump_emit(cprm, (void *) vma->vm_start,
1520                                 vma->vm_end - vma->vm_start))
1521                         return false;
1522 #endif
1523         }
1524         return true;
1525 }
1526
1527 static size_t elf_core_vma_data_size(unsigned long mm_flags)
1528 {
1529         struct vm_area_struct *vma;
1530         size_t size = 0;
1531
1532         for (vma = current->mm->mmap; vma; vma = vma->vm_next)
1533                 if (maydump(vma, mm_flags))
1534                         size += vma->vm_end - vma->vm_start;
1535         return size;
1536 }
1537
1538 /*
1539  * Actual dumper
1540  *
1541  * This is a two-pass process; first we find the offsets of the bits,
1542  * and then they are actually written out.  If we run out of core limit
1543  * we just truncate.
1544  */
1545 static int elf_fdpic_core_dump(struct coredump_params *cprm)
1546 {
1547 #define NUM_NOTES       6
1548         int has_dumped = 0;
1549         mm_segment_t fs;
1550         int segs;
1551         int i;
1552         struct vm_area_struct *vma;
1553         struct elfhdr *elf = NULL;
1554         loff_t offset = 0, dataoff;
1555         int numnote;
1556         struct memelfnote *notes = NULL;
1557         struct elf_prstatus *prstatus = NULL;   /* NT_PRSTATUS */
1558         struct elf_prpsinfo *psinfo = NULL;     /* NT_PRPSINFO */
1559         LIST_HEAD(thread_list);
1560         struct list_head *t;
1561         elf_fpregset_t *fpu = NULL;
1562 #ifdef ELF_CORE_COPY_XFPREGS
1563         elf_fpxregset_t *xfpu = NULL;
1564 #endif
1565         int thread_status_size = 0;
1566         elf_addr_t *auxv;
1567         struct elf_phdr *phdr4note = NULL;
1568         struct elf_shdr *shdr4extnum = NULL;
1569         Elf_Half e_phnum;
1570         elf_addr_t e_shoff;
1571         struct core_thread *ct;
1572         struct elf_thread_status *tmp;
1573
1574         /*
1575          * We no longer stop all VM operations.
1576          *
1577          * This is because those proceses that could possibly change map_count
1578          * or the mmap / vma pages are now blocked in do_exit on current
1579          * finishing this core dump.
1580          *
1581          * Only ptrace can touch these memory addresses, but it doesn't change
1582          * the map_count or the pages allocated. So no possibility of crashing
1583          * exists while dumping the mm->vm_next areas to the core file.
1584          */
1585
1586         /* alloc memory for large data structures: too large to be on stack */
1587         elf = kmalloc(sizeof(*elf), GFP_KERNEL);
1588         if (!elf)
1589                 goto cleanup;
1590         prstatus = kzalloc(sizeof(*prstatus), GFP_KERNEL);
1591         if (!prstatus)
1592                 goto cleanup;
1593         psinfo = kmalloc(sizeof(*psinfo), GFP_KERNEL);
1594         if (!psinfo)
1595                 goto cleanup;
1596         notes = kmalloc(NUM_NOTES * sizeof(struct memelfnote), GFP_KERNEL);
1597         if (!notes)
1598                 goto cleanup;
1599         fpu = kmalloc(sizeof(*fpu), GFP_KERNEL);
1600         if (!fpu)
1601                 goto cleanup;
1602 #ifdef ELF_CORE_COPY_XFPREGS
1603         xfpu = kmalloc(sizeof(*xfpu), GFP_KERNEL);
1604         if (!xfpu)
1605                 goto cleanup;
1606 #endif
1607
1608         for (ct = current->mm->core_state->dumper.next;
1609                                         ct; ct = ct->next) {
1610                 tmp = kzalloc(sizeof(*tmp), GFP_KERNEL);
1611                 if (!tmp)
1612                         goto cleanup;
1613
1614                 tmp->thread = ct->task;
1615                 list_add(&tmp->list, &thread_list);
1616         }
1617
1618         list_for_each(t, &thread_list) {
1619                 struct elf_thread_status *tmp;
1620                 int sz;
1621
1622                 tmp = list_entry(t, struct elf_thread_status, list);
1623                 sz = elf_dump_thread_status(cprm->siginfo->si_signo, tmp);
1624                 thread_status_size += sz;
1625         }
1626
1627         /* now collect the dump for the current */
1628         fill_prstatus(prstatus, current, cprm->siginfo->si_signo);
1629         elf_core_copy_regs(&prstatus->pr_reg, cprm->regs);
1630
1631         segs = current->mm->map_count;
1632         segs += elf_core_extra_phdrs();
1633
1634         /* for notes section */
1635         segs++;
1636
1637         /* If segs > PN_XNUM(0xffff), then e_phnum overflows. To avoid
1638          * this, kernel supports extended numbering. Have a look at
1639          * include/linux/elf.h for further information. */
1640         e_phnum = segs > PN_XNUM ? PN_XNUM : segs;
1641
1642         /* Set up header */
1643         fill_elf_fdpic_header(elf, e_phnum);
1644
1645         has_dumped = 1;
1646         /*
1647          * Set up the notes in similar form to SVR4 core dumps made
1648          * with info from their /proc.
1649          */
1650
1651         fill_note(notes + 0, "CORE", NT_PRSTATUS, sizeof(*prstatus), prstatus);
1652         fill_psinfo(psinfo, current->group_leader, current->mm);
1653         fill_note(notes + 1, "CORE", NT_PRPSINFO, sizeof(*psinfo), psinfo);
1654
1655         numnote = 2;
1656
1657         auxv = (elf_addr_t *) current->mm->saved_auxv;
1658
1659         i = 0;
1660         do
1661                 i += 2;
1662         while (auxv[i - 2] != AT_NULL);
1663         fill_note(&notes[numnote++], "CORE", NT_AUXV,
1664                   i * sizeof(elf_addr_t), auxv);
1665
1666         /* Try to dump the FPU. */
1667         if ((prstatus->pr_fpvalid =
1668              elf_core_copy_task_fpregs(current, cprm->regs, fpu)))
1669                 fill_note(notes + numnote++,
1670                           "CORE", NT_PRFPREG, sizeof(*fpu), fpu);
1671 #ifdef ELF_CORE_COPY_XFPREGS
1672         if (elf_core_copy_task_xfpregs(current, xfpu))
1673                 fill_note(notes + numnote++,
1674                           "LINUX", ELF_CORE_XFPREG_TYPE, sizeof(*xfpu), xfpu);
1675 #endif
1676
1677         fs = get_fs();
1678         set_fs(KERNEL_DS);
1679
1680         offset += sizeof(*elf);                         /* Elf header */
1681         offset += segs * sizeof(struct elf_phdr);       /* Program headers */
1682
1683         /* Write notes phdr entry */
1684         {
1685                 int sz = 0;
1686
1687                 for (i = 0; i < numnote; i++)
1688                         sz += notesize(notes + i);
1689
1690                 sz += thread_status_size;
1691
1692                 phdr4note = kmalloc(sizeof(*phdr4note), GFP_KERNEL);
1693                 if (!phdr4note)
1694                         goto end_coredump;
1695
1696                 fill_elf_note_phdr(phdr4note, sz, offset);
1697                 offset += sz;
1698         }
1699
1700         /* Page-align dumped data */
1701         dataoff = offset = roundup(offset, ELF_EXEC_PAGESIZE);
1702
1703         offset += elf_core_vma_data_size(cprm->mm_flags);
1704         offset += elf_core_extra_data_size();
1705         e_shoff = offset;
1706
1707         if (e_phnum == PN_XNUM) {
1708                 shdr4extnum = kmalloc(sizeof(*shdr4extnum), GFP_KERNEL);
1709                 if (!shdr4extnum)
1710                         goto end_coredump;
1711                 fill_extnum_info(elf, shdr4extnum, e_shoff, segs);
1712         }
1713
1714         offset = dataoff;
1715
1716         if (!dump_emit(cprm, elf, sizeof(*elf)))
1717                 goto end_coredump;
1718
1719         if (!dump_emit(cprm, phdr4note, sizeof(*phdr4note)))
1720                 goto end_coredump;
1721
1722         /* write program headers for segments dump */
1723         for (vma = current->mm->mmap; vma; vma = vma->vm_next) {
1724                 struct elf_phdr phdr;
1725                 size_t sz;
1726
1727                 sz = vma->vm_end - vma->vm_start;
1728
1729                 phdr.p_type = PT_LOAD;
1730                 phdr.p_offset = offset;
1731                 phdr.p_vaddr = vma->vm_start;
1732                 phdr.p_paddr = 0;
1733                 phdr.p_filesz = maydump(vma, cprm->mm_flags) ? sz : 0;
1734                 phdr.p_memsz = sz;
1735                 offset += phdr.p_filesz;
1736                 phdr.p_flags = vma->vm_flags & VM_READ ? PF_R : 0;
1737                 if (vma->vm_flags & VM_WRITE)
1738                         phdr.p_flags |= PF_W;
1739                 if (vma->vm_flags & VM_EXEC)
1740                         phdr.p_flags |= PF_X;
1741                 phdr.p_align = ELF_EXEC_PAGESIZE;
1742
1743                 if (!dump_emit(cprm, &phdr, sizeof(phdr)))
1744                         goto end_coredump;
1745         }
1746
1747         if (!elf_core_write_extra_phdrs(cprm, offset))
1748                 goto end_coredump;
1749
1750         /* write out the notes section */
1751         for (i = 0; i < numnote; i++)
1752                 if (!writenote(notes + i, cprm))
1753                         goto end_coredump;
1754
1755         /* write out the thread status notes section */
1756         list_for_each(t, &thread_list) {
1757                 struct elf_thread_status *tmp =
1758                                 list_entry(t, struct elf_thread_status, list);
1759
1760                 for (i = 0; i < tmp->num_notes; i++)
1761                         if (!writenote(&tmp->notes[i], cprm))
1762                                 goto end_coredump;
1763         }
1764
1765         if (!dump_skip(cprm, dataoff - cprm->written))
1766                 goto end_coredump;
1767
1768         if (!elf_fdpic_dump_segments(cprm))
1769                 goto end_coredump;
1770
1771         if (!elf_core_write_extra_data(cprm))
1772                 goto end_coredump;
1773
1774         if (e_phnum == PN_XNUM) {
1775                 if (!dump_emit(cprm, shdr4extnum, sizeof(*shdr4extnum)))
1776                         goto end_coredump;
1777         }
1778
1779         if (cprm->file->f_pos != offset) {
1780                 /* Sanity check */
1781                 printk(KERN_WARNING
1782                        "elf_core_dump: file->f_pos (%lld) != offset (%lld)\n",
1783                        cprm->file->f_pos, offset);
1784         }
1785
1786 end_coredump:
1787         set_fs(fs);
1788
1789 cleanup:
1790         while (!list_empty(&thread_list)) {
1791                 struct list_head *tmp = thread_list.next;
1792                 list_del(tmp);
1793                 kfree(list_entry(tmp, struct elf_thread_status, list));
1794         }
1795         kfree(phdr4note);
1796         kfree(elf);
1797         kfree(prstatus);
1798         kfree(psinfo);
1799         kfree(notes);
1800         kfree(fpu);
1801         kfree(shdr4extnum);
1802 #ifdef ELF_CORE_COPY_XFPREGS
1803         kfree(xfpu);
1804 #endif
1805         return has_dumped;
1806 #undef NUM_NOTES
1807 }
1808
1809 #endif          /* CONFIG_ELF_CORE */