xref: /linux-6.15/fs/binfmt_elf.c (revision 8ed2ef21)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * linux/fs/binfmt_elf.c
4  *
5  * These are the functions used to load ELF format executables as used
6  * on SVr4 machines.  Information on the format may be found in the book
7  * "UNIX SYSTEM V RELEASE 4 Programmers Guide: Ansi C and Programming Support
8  * Tools".
9  *
10  * Copyright 1993, 1994: Eric Youngdale ([email protected]).
11  */
12 
13 #include <linux/module.h>
14 #include <linux/kernel.h>
15 #include <linux/fs.h>
16 #include <linux/log2.h>
17 #include <linux/mm.h>
18 #include <linux/mman.h>
19 #include <linux/errno.h>
20 #include <linux/signal.h>
21 #include <linux/binfmts.h>
22 #include <linux/string.h>
23 #include <linux/file.h>
24 #include <linux/slab.h>
25 #include <linux/personality.h>
26 #include <linux/elfcore.h>
27 #include <linux/init.h>
28 #include <linux/highuid.h>
29 #include <linux/compiler.h>
30 #include <linux/highmem.h>
31 #include <linux/hugetlb.h>
32 #include <linux/pagemap.h>
33 #include <linux/vmalloc.h>
34 #include <linux/security.h>
35 #include <linux/random.h>
36 #include <linux/elf.h>
37 #include <linux/elf-randomize.h>
38 #include <linux/utsname.h>
39 #include <linux/coredump.h>
40 #include <linux/sched.h>
41 #include <linux/sched/coredump.h>
42 #include <linux/sched/task_stack.h>
43 #include <linux/sched/cputime.h>
44 #include <linux/sizes.h>
45 #include <linux/types.h>
46 #include <linux/cred.h>
47 #include <linux/dax.h>
48 #include <linux/uaccess.h>
49 #include <linux/rseq.h>
50 #include <asm/param.h>
51 #include <asm/page.h>
52 
53 #ifndef ELF_COMPAT
54 #define ELF_COMPAT 0
55 #endif
56 
57 #ifndef user_long_t
58 #define user_long_t long
59 #endif
60 #ifndef user_siginfo_t
61 #define user_siginfo_t siginfo_t
62 #endif
63 
64 /* That's for binfmt_elf_fdpic to deal with */
65 #ifndef elf_check_fdpic
66 #define elf_check_fdpic(ex) false
67 #endif
68 
69 static int load_elf_binary(struct linux_binprm *bprm);
70 
71 #ifdef CONFIG_USELIB
72 static int load_elf_library(struct file *);
73 #else
74 #define load_elf_library NULL
75 #endif
76 
77 /*
78  * If we don't support core dumping, then supply a NULL so we
79  * don't even try.
80  */
81 #ifdef CONFIG_ELF_CORE
82 static int elf_core_dump(struct coredump_params *cprm);
83 #else
84 #define elf_core_dump	NULL
85 #endif
86 
87 #if ELF_EXEC_PAGESIZE > PAGE_SIZE
88 #define ELF_MIN_ALIGN	ELF_EXEC_PAGESIZE
89 #else
90 #define ELF_MIN_ALIGN	PAGE_SIZE
91 #endif
92 
93 #ifndef ELF_CORE_EFLAGS
94 #define ELF_CORE_EFLAGS	0
95 #endif
96 
97 #define ELF_PAGESTART(_v) ((_v) & ~(int)(ELF_MIN_ALIGN-1))
98 #define ELF_PAGEOFFSET(_v) ((_v) & (ELF_MIN_ALIGN-1))
99 #define ELF_PAGEALIGN(_v) (((_v) + ELF_MIN_ALIGN - 1) & ~(ELF_MIN_ALIGN - 1))
100 
101 static struct linux_binfmt elf_format = {
102 	.module		= THIS_MODULE,
103 	.load_binary	= load_elf_binary,
104 	.load_shlib	= load_elf_library,
105 #ifdef CONFIG_COREDUMP
106 	.core_dump	= elf_core_dump,
107 	.min_coredump	= ELF_EXEC_PAGESIZE,
108 #endif
109 };
110 
111 #define BAD_ADDR(x) (unlikely((unsigned long)(x) >= TASK_SIZE))
112 
113 /* We need to explicitly zero any fractional pages
114    after the data section (i.e. bss).  This would
115    contain the junk from the file that should not
116    be in memory
117  */
118 static int padzero(unsigned long elf_bss)
119 {
120 	unsigned long nbyte;
121 
122 	nbyte = ELF_PAGEOFFSET(elf_bss);
123 	if (nbyte) {
124 		nbyte = ELF_MIN_ALIGN - nbyte;
125 		if (clear_user((void __user *) elf_bss, nbyte))
126 			return -EFAULT;
127 	}
128 	return 0;
129 }
130 
131 /* Let's use some macros to make this stack manipulation a little clearer */
132 #ifdef CONFIG_STACK_GROWSUP
133 #define STACK_ADD(sp, items) ((elf_addr_t __user *)(sp) + (items))
134 #define STACK_ROUND(sp, items) \
135 	((15 + (unsigned long) ((sp) + (items))) &~ 15UL)
136 #define STACK_ALLOC(sp, len) ({ \
137 	elf_addr_t __user *old_sp = (elf_addr_t __user *)sp; sp += len; \
138 	old_sp; })
139 #else
140 #define STACK_ADD(sp, items) ((elf_addr_t __user *)(sp) - (items))
141 #define STACK_ROUND(sp, items) \
142 	(((unsigned long) (sp - items)) &~ 15UL)
143 #define STACK_ALLOC(sp, len) (sp -= len)
144 #endif
145 
146 #ifndef ELF_BASE_PLATFORM
147 /*
148  * AT_BASE_PLATFORM indicates the "real" hardware/microarchitecture.
149  * If the arch defines ELF_BASE_PLATFORM (in asm/elf.h), the value
150  * will be copied to the user stack in the same manner as AT_PLATFORM.
151  */
152 #define ELF_BASE_PLATFORM NULL
153 #endif
154 
155 static int
156 create_elf_tables(struct linux_binprm *bprm, const struct elfhdr *exec,
157 		unsigned long interp_load_addr,
158 		unsigned long e_entry, unsigned long phdr_addr)
159 {
160 	struct mm_struct *mm = current->mm;
161 	unsigned long p = bprm->p;
162 	int argc = bprm->argc;
163 	int envc = bprm->envc;
164 	elf_addr_t __user *sp;
165 	elf_addr_t __user *u_platform;
166 	elf_addr_t __user *u_base_platform;
167 	elf_addr_t __user *u_rand_bytes;
168 	const char *k_platform = ELF_PLATFORM;
169 	const char *k_base_platform = ELF_BASE_PLATFORM;
170 	unsigned char k_rand_bytes[16];
171 	int items;
172 	elf_addr_t *elf_info;
173 	elf_addr_t flags = 0;
174 	int ei_index;
175 	const struct cred *cred = current_cred();
176 	struct vm_area_struct *vma;
177 
178 	/*
179 	 * In some cases (e.g. Hyper-Threading), we want to avoid L1
180 	 * evictions by the processes running on the same package. One
181 	 * thing we can do is to shuffle the initial stack for them.
182 	 */
183 
184 	p = arch_align_stack(p);
185 
186 	/*
187 	 * If this architecture has a platform capability string, copy it
188 	 * to userspace.  In some cases (Sparc), this info is impossible
189 	 * for userspace to get any other way, in others (i386) it is
190 	 * merely difficult.
191 	 */
192 	u_platform = NULL;
193 	if (k_platform) {
194 		size_t len = strlen(k_platform) + 1;
195 
196 		u_platform = (elf_addr_t __user *)STACK_ALLOC(p, len);
197 		if (copy_to_user(u_platform, k_platform, len))
198 			return -EFAULT;
199 	}
200 
201 	/*
202 	 * If this architecture has a "base" platform capability
203 	 * string, copy it to userspace.
204 	 */
205 	u_base_platform = NULL;
206 	if (k_base_platform) {
207 		size_t len = strlen(k_base_platform) + 1;
208 
209 		u_base_platform = (elf_addr_t __user *)STACK_ALLOC(p, len);
210 		if (copy_to_user(u_base_platform, k_base_platform, len))
211 			return -EFAULT;
212 	}
213 
214 	/*
215 	 * Generate 16 random bytes for userspace PRNG seeding.
216 	 */
217 	get_random_bytes(k_rand_bytes, sizeof(k_rand_bytes));
218 	u_rand_bytes = (elf_addr_t __user *)
219 		       STACK_ALLOC(p, sizeof(k_rand_bytes));
220 	if (copy_to_user(u_rand_bytes, k_rand_bytes, sizeof(k_rand_bytes)))
221 		return -EFAULT;
222 
223 	/* Create the ELF interpreter info */
224 	elf_info = (elf_addr_t *)mm->saved_auxv;
225 	/* update AT_VECTOR_SIZE_BASE if the number of NEW_AUX_ENT() changes */
226 #define NEW_AUX_ENT(id, val) \
227 	do { \
228 		*elf_info++ = id; \
229 		*elf_info++ = val; \
230 	} while (0)
231 
232 #ifdef ARCH_DLINFO
233 	/*
234 	 * ARCH_DLINFO must come first so PPC can do its special alignment of
235 	 * AUXV.
236 	 * update AT_VECTOR_SIZE_ARCH if the number of NEW_AUX_ENT() in
237 	 * ARCH_DLINFO changes
238 	 */
239 	ARCH_DLINFO;
240 #endif
241 	NEW_AUX_ENT(AT_HWCAP, ELF_HWCAP);
242 	NEW_AUX_ENT(AT_PAGESZ, ELF_EXEC_PAGESIZE);
243 	NEW_AUX_ENT(AT_CLKTCK, CLOCKS_PER_SEC);
244 	NEW_AUX_ENT(AT_PHDR, phdr_addr);
245 	NEW_AUX_ENT(AT_PHENT, sizeof(struct elf_phdr));
246 	NEW_AUX_ENT(AT_PHNUM, exec->e_phnum);
247 	NEW_AUX_ENT(AT_BASE, interp_load_addr);
248 	if (bprm->interp_flags & BINPRM_FLAGS_PRESERVE_ARGV0)
249 		flags |= AT_FLAGS_PRESERVE_ARGV0;
250 	NEW_AUX_ENT(AT_FLAGS, flags);
251 	NEW_AUX_ENT(AT_ENTRY, e_entry);
252 	NEW_AUX_ENT(AT_UID, from_kuid_munged(cred->user_ns, cred->uid));
253 	NEW_AUX_ENT(AT_EUID, from_kuid_munged(cred->user_ns, cred->euid));
254 	NEW_AUX_ENT(AT_GID, from_kgid_munged(cred->user_ns, cred->gid));
255 	NEW_AUX_ENT(AT_EGID, from_kgid_munged(cred->user_ns, cred->egid));
256 	NEW_AUX_ENT(AT_SECURE, bprm->secureexec);
257 	NEW_AUX_ENT(AT_RANDOM, (elf_addr_t)(unsigned long)u_rand_bytes);
258 #ifdef ELF_HWCAP2
259 	NEW_AUX_ENT(AT_HWCAP2, ELF_HWCAP2);
260 #endif
261 	NEW_AUX_ENT(AT_EXECFN, bprm->exec);
262 	if (k_platform) {
263 		NEW_AUX_ENT(AT_PLATFORM,
264 			    (elf_addr_t)(unsigned long)u_platform);
265 	}
266 	if (k_base_platform) {
267 		NEW_AUX_ENT(AT_BASE_PLATFORM,
268 			    (elf_addr_t)(unsigned long)u_base_platform);
269 	}
270 	if (bprm->have_execfd) {
271 		NEW_AUX_ENT(AT_EXECFD, bprm->execfd);
272 	}
273 #ifdef CONFIG_RSEQ
274 	NEW_AUX_ENT(AT_RSEQ_FEATURE_SIZE, offsetof(struct rseq, end));
275 	NEW_AUX_ENT(AT_RSEQ_ALIGN, __alignof__(struct rseq));
276 #endif
277 #undef NEW_AUX_ENT
278 	/* AT_NULL is zero; clear the rest too */
279 	memset(elf_info, 0, (char *)mm->saved_auxv +
280 			sizeof(mm->saved_auxv) - (char *)elf_info);
281 
282 	/* And advance past the AT_NULL entry.  */
283 	elf_info += 2;
284 
285 	ei_index = elf_info - (elf_addr_t *)mm->saved_auxv;
286 	sp = STACK_ADD(p, ei_index);
287 
288 	items = (argc + 1) + (envc + 1) + 1;
289 	bprm->p = STACK_ROUND(sp, items);
290 
291 	/* Point sp at the lowest address on the stack */
292 #ifdef CONFIG_STACK_GROWSUP
293 	sp = (elf_addr_t __user *)bprm->p - items - ei_index;
294 	bprm->exec = (unsigned long)sp; /* XXX: PARISC HACK */
295 #else
296 	sp = (elf_addr_t __user *)bprm->p;
297 #endif
298 
299 
300 	/*
301 	 * Grow the stack manually; some architectures have a limit on how
302 	 * far ahead a user-space access may be in order to grow the stack.
303 	 */
304 	if (mmap_write_lock_killable(mm))
305 		return -EINTR;
306 	vma = find_extend_vma_locked(mm, bprm->p);
307 	mmap_write_unlock(mm);
308 	if (!vma)
309 		return -EFAULT;
310 
311 	/* Now, let's put argc (and argv, envp if appropriate) on the stack */
312 	if (put_user(argc, sp++))
313 		return -EFAULT;
314 
315 	/* Populate list of argv pointers back to argv strings. */
316 	p = mm->arg_end = mm->arg_start;
317 	while (argc-- > 0) {
318 		size_t len;
319 		if (put_user((elf_addr_t)p, sp++))
320 			return -EFAULT;
321 		len = strnlen_user((void __user *)p, MAX_ARG_STRLEN);
322 		if (!len || len > MAX_ARG_STRLEN)
323 			return -EINVAL;
324 		p += len;
325 	}
326 	if (put_user(0, sp++))
327 		return -EFAULT;
328 	mm->arg_end = p;
329 
330 	/* Populate list of envp pointers back to envp strings. */
331 	mm->env_end = mm->env_start = p;
332 	while (envc-- > 0) {
333 		size_t len;
334 		if (put_user((elf_addr_t)p, sp++))
335 			return -EFAULT;
336 		len = strnlen_user((void __user *)p, MAX_ARG_STRLEN);
337 		if (!len || len > MAX_ARG_STRLEN)
338 			return -EINVAL;
339 		p += len;
340 	}
341 	if (put_user(0, sp++))
342 		return -EFAULT;
343 	mm->env_end = p;
344 
345 	/* Put the elf_info on the stack in the right place.  */
346 	if (copy_to_user(sp, mm->saved_auxv, ei_index * sizeof(elf_addr_t)))
347 		return -EFAULT;
348 	return 0;
349 }
350 
351 static unsigned long elf_map(struct file *filep, unsigned long addr,
352 		const struct elf_phdr *eppnt, int prot, int type,
353 		unsigned long total_size)
354 {
355 	unsigned long map_addr;
356 	unsigned long size = eppnt->p_filesz + ELF_PAGEOFFSET(eppnt->p_vaddr);
357 	unsigned long off = eppnt->p_offset - ELF_PAGEOFFSET(eppnt->p_vaddr);
358 	addr = ELF_PAGESTART(addr);
359 	size = ELF_PAGEALIGN(size);
360 
361 	/* mmap() will return -EINVAL if given a zero size, but a
362 	 * segment with zero filesize is perfectly valid */
363 	if (!size)
364 		return addr;
365 
366 	/*
367 	* total_size is the size of the ELF (interpreter) image.
368 	* The _first_ mmap needs to know the full size, otherwise
369 	* randomization might put this image into an overlapping
370 	* position with the ELF binary image. (since size < total_size)
371 	* So we first map the 'big' image - and unmap the remainder at
372 	* the end. (which unmap is needed for ELF images with holes.)
373 	*/
374 	if (total_size) {
375 		total_size = ELF_PAGEALIGN(total_size);
376 		map_addr = vm_mmap(filep, addr, total_size, prot, type, off);
377 		if (!BAD_ADDR(map_addr))
378 			vm_munmap(map_addr+size, total_size-size);
379 	} else
380 		map_addr = vm_mmap(filep, addr, size, prot, type, off);
381 
382 	if ((type & MAP_FIXED_NOREPLACE) &&
383 	    PTR_ERR((void *)map_addr) == -EEXIST)
384 		pr_info("%d (%s): Uhuuh, elf segment at %px requested but the memory is mapped already\n",
385 			task_pid_nr(current), current->comm, (void *)addr);
386 
387 	return(map_addr);
388 }
389 
390 static unsigned long elf_load(struct file *filep, unsigned long addr,
391 		const struct elf_phdr *eppnt, int prot, int type,
392 		unsigned long total_size)
393 {
394 	unsigned long zero_start, zero_end;
395 	unsigned long map_addr;
396 
397 	if (eppnt->p_filesz) {
398 		map_addr = elf_map(filep, addr, eppnt, prot, type, total_size);
399 		if (BAD_ADDR(map_addr))
400 			return map_addr;
401 		if (eppnt->p_memsz > eppnt->p_filesz) {
402 			zero_start = map_addr + ELF_PAGEOFFSET(eppnt->p_vaddr) +
403 				eppnt->p_filesz;
404 			zero_end = map_addr + ELF_PAGEOFFSET(eppnt->p_vaddr) +
405 				eppnt->p_memsz;
406 
407 			/* Zero the end of the last mapped page */
408 			padzero(zero_start);
409 		}
410 	} else {
411 		map_addr = zero_start = ELF_PAGESTART(addr);
412 		zero_end = zero_start + ELF_PAGEOFFSET(eppnt->p_vaddr) +
413 			eppnt->p_memsz;
414 	}
415 	if (eppnt->p_memsz > eppnt->p_filesz) {
416 		/*
417 		 * Map the last of the segment.
418 		 * If the header is requesting these pages to be
419 		 * executable, honour that (ppc32 needs this).
420 		 */
421 		int error;
422 
423 		zero_start = ELF_PAGEALIGN(zero_start);
424 		zero_end = ELF_PAGEALIGN(zero_end);
425 
426 		error = vm_brk_flags(zero_start, zero_end - zero_start,
427 				     prot & PROT_EXEC ? VM_EXEC : 0);
428 		if (error)
429 			map_addr = error;
430 	}
431 	return map_addr;
432 }
433 
434 
435 static unsigned long total_mapping_size(const struct elf_phdr *phdr, int nr)
436 {
437 	elf_addr_t min_addr = -1;
438 	elf_addr_t max_addr = 0;
439 	bool pt_load = false;
440 	int i;
441 
442 	for (i = 0; i < nr; i++) {
443 		if (phdr[i].p_type == PT_LOAD) {
444 			min_addr = min(min_addr, ELF_PAGESTART(phdr[i].p_vaddr));
445 			max_addr = max(max_addr, phdr[i].p_vaddr + phdr[i].p_memsz);
446 			pt_load = true;
447 		}
448 	}
449 	return pt_load ? (max_addr - min_addr) : 0;
450 }
451 
452 static int elf_read(struct file *file, void *buf, size_t len, loff_t pos)
453 {
454 	ssize_t rv;
455 
456 	rv = kernel_read(file, buf, len, &pos);
457 	if (unlikely(rv != len)) {
458 		return (rv < 0) ? rv : -EIO;
459 	}
460 	return 0;
461 }
462 
463 static unsigned long maximum_alignment(struct elf_phdr *cmds, int nr)
464 {
465 	unsigned long alignment = 0;
466 	int i;
467 
468 	for (i = 0; i < nr; i++) {
469 		if (cmds[i].p_type == PT_LOAD) {
470 			unsigned long p_align = cmds[i].p_align;
471 
472 			/* skip non-power of two alignments as invalid */
473 			if (!is_power_of_2(p_align))
474 				continue;
475 			alignment = max(alignment, p_align);
476 		}
477 	}
478 
479 	/* ensure we align to at least one page */
480 	return ELF_PAGEALIGN(alignment);
481 }
482 
483 /**
484  * load_elf_phdrs() - load ELF program headers
485  * @elf_ex:   ELF header of the binary whose program headers should be loaded
486  * @elf_file: the opened ELF binary file
487  *
488  * Loads ELF program headers from the binary file elf_file, which has the ELF
489  * header pointed to by elf_ex, into a newly allocated array. The caller is
490  * responsible for freeing the allocated data. Returns NULL upon failure.
491  */
492 static struct elf_phdr *load_elf_phdrs(const struct elfhdr *elf_ex,
493 				       struct file *elf_file)
494 {
495 	struct elf_phdr *elf_phdata = NULL;
496 	int retval = -1;
497 	unsigned int size;
498 
499 	/*
500 	 * If the size of this structure has changed, then punt, since
501 	 * we will be doing the wrong thing.
502 	 */
503 	if (elf_ex->e_phentsize != sizeof(struct elf_phdr))
504 		goto out;
505 
506 	/* Sanity check the number of program headers... */
507 	/* ...and their total size. */
508 	size = sizeof(struct elf_phdr) * elf_ex->e_phnum;
509 	if (size == 0 || size > 65536 || size > ELF_MIN_ALIGN)
510 		goto out;
511 
512 	elf_phdata = kmalloc(size, GFP_KERNEL);
513 	if (!elf_phdata)
514 		goto out;
515 
516 	/* Read in the program headers */
517 	retval = elf_read(elf_file, elf_phdata, size, elf_ex->e_phoff);
518 
519 out:
520 	if (retval) {
521 		kfree(elf_phdata);
522 		elf_phdata = NULL;
523 	}
524 	return elf_phdata;
525 }
526 
527 #ifndef CONFIG_ARCH_BINFMT_ELF_STATE
528 
529 /**
530  * struct arch_elf_state - arch-specific ELF loading state
531  *
532  * This structure is used to preserve architecture specific data during
533  * the loading of an ELF file, throughout the checking of architecture
534  * specific ELF headers & through to the point where the ELF load is
535  * known to be proceeding (ie. SET_PERSONALITY).
536  *
537  * This implementation is a dummy for architectures which require no
538  * specific state.
539  */
540 struct arch_elf_state {
541 };
542 
543 #define INIT_ARCH_ELF_STATE {}
544 
545 /**
546  * arch_elf_pt_proc() - check a PT_LOPROC..PT_HIPROC ELF program header
547  * @ehdr:	The main ELF header
548  * @phdr:	The program header to check
549  * @elf:	The open ELF file
550  * @is_interp:	True if the phdr is from the interpreter of the ELF being
551  *		loaded, else false.
552  * @state:	Architecture-specific state preserved throughout the process
553  *		of loading the ELF.
554  *
555  * Inspects the program header phdr to validate its correctness and/or
556  * suitability for the system. Called once per ELF program header in the
557  * range PT_LOPROC to PT_HIPROC, for both the ELF being loaded and its
558  * interpreter.
559  *
560  * Return: Zero to proceed with the ELF load, non-zero to fail the ELF load
561  *         with that return code.
562  */
563 static inline int arch_elf_pt_proc(struct elfhdr *ehdr,
564 				   struct elf_phdr *phdr,
565 				   struct file *elf, bool is_interp,
566 				   struct arch_elf_state *state)
567 {
568 	/* Dummy implementation, always proceed */
569 	return 0;
570 }
571 
572 /**
573  * arch_check_elf() - check an ELF executable
574  * @ehdr:	The main ELF header
575  * @has_interp:	True if the ELF has an interpreter, else false.
576  * @interp_ehdr: The interpreter's ELF header
577  * @state:	Architecture-specific state preserved throughout the process
578  *		of loading the ELF.
579  *
580  * Provides a final opportunity for architecture code to reject the loading
581  * of the ELF & cause an exec syscall to return an error. This is called after
582  * all program headers to be checked by arch_elf_pt_proc have been.
583  *
584  * Return: Zero to proceed with the ELF load, non-zero to fail the ELF load
585  *         with that return code.
586  */
587 static inline int arch_check_elf(struct elfhdr *ehdr, bool has_interp,
588 				 struct elfhdr *interp_ehdr,
589 				 struct arch_elf_state *state)
590 {
591 	/* Dummy implementation, always proceed */
592 	return 0;
593 }
594 
595 #endif /* !CONFIG_ARCH_BINFMT_ELF_STATE */
596 
597 static inline int make_prot(u32 p_flags, struct arch_elf_state *arch_state,
598 			    bool has_interp, bool is_interp)
599 {
600 	int prot = 0;
601 
602 	if (p_flags & PF_R)
603 		prot |= PROT_READ;
604 	if (p_flags & PF_W)
605 		prot |= PROT_WRITE;
606 	if (p_flags & PF_X)
607 		prot |= PROT_EXEC;
608 
609 	return arch_elf_adjust_prot(prot, arch_state, has_interp, is_interp);
610 }
611 
612 /* This is much more generalized than the library routine read function,
613    so we keep this separate.  Technically the library read function
614    is only provided so that we can read a.out libraries that have
615    an ELF header */
616 
617 static unsigned long load_elf_interp(struct elfhdr *interp_elf_ex,
618 		struct file *interpreter,
619 		unsigned long no_base, struct elf_phdr *interp_elf_phdata,
620 		struct arch_elf_state *arch_state)
621 {
622 	struct elf_phdr *eppnt;
623 	unsigned long load_addr = 0;
624 	int load_addr_set = 0;
625 	unsigned long last_bss = 0, elf_bss = 0;
626 	int bss_prot = 0;
627 	unsigned long error = ~0UL;
628 	unsigned long total_size;
629 	int i;
630 
631 	/* First of all, some simple consistency checks */
632 	if (interp_elf_ex->e_type != ET_EXEC &&
633 	    interp_elf_ex->e_type != ET_DYN)
634 		goto out;
635 	if (!elf_check_arch(interp_elf_ex) ||
636 	    elf_check_fdpic(interp_elf_ex))
637 		goto out;
638 	if (!interpreter->f_op->mmap)
639 		goto out;
640 
641 	total_size = total_mapping_size(interp_elf_phdata,
642 					interp_elf_ex->e_phnum);
643 	if (!total_size) {
644 		error = -EINVAL;
645 		goto out;
646 	}
647 
648 	eppnt = interp_elf_phdata;
649 	for (i = 0; i < interp_elf_ex->e_phnum; i++, eppnt++) {
650 		if (eppnt->p_type == PT_LOAD) {
651 			int elf_type = MAP_PRIVATE;
652 			int elf_prot = make_prot(eppnt->p_flags, arch_state,
653 						 true, true);
654 			unsigned long vaddr = 0;
655 			unsigned long k, map_addr;
656 
657 			vaddr = eppnt->p_vaddr;
658 			if (interp_elf_ex->e_type == ET_EXEC || load_addr_set)
659 				elf_type |= MAP_FIXED;
660 			else if (no_base && interp_elf_ex->e_type == ET_DYN)
661 				load_addr = -vaddr;
662 
663 			map_addr = elf_map(interpreter, load_addr + vaddr,
664 					eppnt, elf_prot, elf_type, total_size);
665 			total_size = 0;
666 			error = map_addr;
667 			if (BAD_ADDR(map_addr))
668 				goto out;
669 
670 			if (!load_addr_set &&
671 			    interp_elf_ex->e_type == ET_DYN) {
672 				load_addr = map_addr - ELF_PAGESTART(vaddr);
673 				load_addr_set = 1;
674 			}
675 
676 			/*
677 			 * Check to see if the section's size will overflow the
678 			 * allowed task size. Note that p_filesz must always be
679 			 * <= p_memsize so it's only necessary to check p_memsz.
680 			 */
681 			k = load_addr + eppnt->p_vaddr;
682 			if (BAD_ADDR(k) ||
683 			    eppnt->p_filesz > eppnt->p_memsz ||
684 			    eppnt->p_memsz > TASK_SIZE ||
685 			    TASK_SIZE - eppnt->p_memsz < k) {
686 				error = -ENOMEM;
687 				goto out;
688 			}
689 
690 			/*
691 			 * Find the end of the file mapping for this phdr, and
692 			 * keep track of the largest address we see for this.
693 			 */
694 			k = load_addr + eppnt->p_vaddr + eppnt->p_filesz;
695 			if (k > elf_bss)
696 				elf_bss = k;
697 
698 			/*
699 			 * Do the same thing for the memory mapping - between
700 			 * elf_bss and last_bss is the bss section.
701 			 */
702 			k = load_addr + eppnt->p_vaddr + eppnt->p_memsz;
703 			if (k > last_bss) {
704 				last_bss = k;
705 				bss_prot = elf_prot;
706 			}
707 		}
708 	}
709 
710 	/*
711 	 * Now fill out the bss section: first pad the last page from
712 	 * the file up to the page boundary, and zero it from elf_bss
713 	 * up to the end of the page.
714 	 */
715 	if (padzero(elf_bss)) {
716 		error = -EFAULT;
717 		goto out;
718 	}
719 	/*
720 	 * Next, align both the file and mem bss up to the page size,
721 	 * since this is where elf_bss was just zeroed up to, and where
722 	 * last_bss will end after the vm_brk_flags() below.
723 	 */
724 	elf_bss = ELF_PAGEALIGN(elf_bss);
725 	last_bss = ELF_PAGEALIGN(last_bss);
726 	/* Finally, if there is still more bss to allocate, do it. */
727 	if (last_bss > elf_bss) {
728 		error = vm_brk_flags(elf_bss, last_bss - elf_bss,
729 				bss_prot & PROT_EXEC ? VM_EXEC : 0);
730 		if (error)
731 			goto out;
732 	}
733 
734 	error = load_addr;
735 out:
736 	return error;
737 }
738 
739 /*
740  * These are the functions used to load ELF style executables and shared
741  * libraries.  There is no binary dependent code anywhere else.
742  */
743 
744 static int parse_elf_property(const char *data, size_t *off, size_t datasz,
745 			      struct arch_elf_state *arch,
746 			      bool have_prev_type, u32 *prev_type)
747 {
748 	size_t o, step;
749 	const struct gnu_property *pr;
750 	int ret;
751 
752 	if (*off == datasz)
753 		return -ENOENT;
754 
755 	if (WARN_ON_ONCE(*off > datasz || *off % ELF_GNU_PROPERTY_ALIGN))
756 		return -EIO;
757 	o = *off;
758 	datasz -= *off;
759 
760 	if (datasz < sizeof(*pr))
761 		return -ENOEXEC;
762 	pr = (const struct gnu_property *)(data + o);
763 	o += sizeof(*pr);
764 	datasz -= sizeof(*pr);
765 
766 	if (pr->pr_datasz > datasz)
767 		return -ENOEXEC;
768 
769 	WARN_ON_ONCE(o % ELF_GNU_PROPERTY_ALIGN);
770 	step = round_up(pr->pr_datasz, ELF_GNU_PROPERTY_ALIGN);
771 	if (step > datasz)
772 		return -ENOEXEC;
773 
774 	/* Properties are supposed to be unique and sorted on pr_type: */
775 	if (have_prev_type && pr->pr_type <= *prev_type)
776 		return -ENOEXEC;
777 	*prev_type = pr->pr_type;
778 
779 	ret = arch_parse_elf_property(pr->pr_type, data + o,
780 				      pr->pr_datasz, ELF_COMPAT, arch);
781 	if (ret)
782 		return ret;
783 
784 	*off = o + step;
785 	return 0;
786 }
787 
788 #define NOTE_DATA_SZ SZ_1K
789 #define GNU_PROPERTY_TYPE_0_NAME "GNU"
790 #define NOTE_NAME_SZ (sizeof(GNU_PROPERTY_TYPE_0_NAME))
791 
792 static int parse_elf_properties(struct file *f, const struct elf_phdr *phdr,
793 				struct arch_elf_state *arch)
794 {
795 	union {
796 		struct elf_note nhdr;
797 		char data[NOTE_DATA_SZ];
798 	} note;
799 	loff_t pos;
800 	ssize_t n;
801 	size_t off, datasz;
802 	int ret;
803 	bool have_prev_type;
804 	u32 prev_type;
805 
806 	if (!IS_ENABLED(CONFIG_ARCH_USE_GNU_PROPERTY) || !phdr)
807 		return 0;
808 
809 	/* load_elf_binary() shouldn't call us unless this is true... */
810 	if (WARN_ON_ONCE(phdr->p_type != PT_GNU_PROPERTY))
811 		return -ENOEXEC;
812 
813 	/* If the properties are crazy large, that's too bad (for now): */
814 	if (phdr->p_filesz > sizeof(note))
815 		return -ENOEXEC;
816 
817 	pos = phdr->p_offset;
818 	n = kernel_read(f, &note, phdr->p_filesz, &pos);
819 
820 	BUILD_BUG_ON(sizeof(note) < sizeof(note.nhdr) + NOTE_NAME_SZ);
821 	if (n < 0 || n < sizeof(note.nhdr) + NOTE_NAME_SZ)
822 		return -EIO;
823 
824 	if (note.nhdr.n_type != NT_GNU_PROPERTY_TYPE_0 ||
825 	    note.nhdr.n_namesz != NOTE_NAME_SZ ||
826 	    strncmp(note.data + sizeof(note.nhdr),
827 		    GNU_PROPERTY_TYPE_0_NAME, n - sizeof(note.nhdr)))
828 		return -ENOEXEC;
829 
830 	off = round_up(sizeof(note.nhdr) + NOTE_NAME_SZ,
831 		       ELF_GNU_PROPERTY_ALIGN);
832 	if (off > n)
833 		return -ENOEXEC;
834 
835 	if (note.nhdr.n_descsz > n - off)
836 		return -ENOEXEC;
837 	datasz = off + note.nhdr.n_descsz;
838 
839 	have_prev_type = false;
840 	do {
841 		ret = parse_elf_property(note.data, &off, datasz, arch,
842 					 have_prev_type, &prev_type);
843 		have_prev_type = true;
844 	} while (!ret);
845 
846 	return ret == -ENOENT ? 0 : ret;
847 }
848 
849 static int load_elf_binary(struct linux_binprm *bprm)
850 {
851 	struct file *interpreter = NULL; /* to shut gcc up */
852 	unsigned long load_bias = 0, phdr_addr = 0;
853 	int first_pt_load = 1;
854 	unsigned long error;
855 	struct elf_phdr *elf_ppnt, *elf_phdata, *interp_elf_phdata = NULL;
856 	struct elf_phdr *elf_property_phdata = NULL;
857 	unsigned long elf_brk;
858 	int retval, i;
859 	unsigned long elf_entry;
860 	unsigned long e_entry;
861 	unsigned long interp_load_addr = 0;
862 	unsigned long start_code, end_code, start_data, end_data;
863 	unsigned long reloc_func_desc __maybe_unused = 0;
864 	int executable_stack = EXSTACK_DEFAULT;
865 	struct elfhdr *elf_ex = (struct elfhdr *)bprm->buf;
866 	struct elfhdr *interp_elf_ex = NULL;
867 	struct arch_elf_state arch_state = INIT_ARCH_ELF_STATE;
868 	struct mm_struct *mm;
869 	struct pt_regs *regs;
870 
871 	retval = -ENOEXEC;
872 	/* First of all, some simple consistency checks */
873 	if (memcmp(elf_ex->e_ident, ELFMAG, SELFMAG) != 0)
874 		goto out;
875 
876 	if (elf_ex->e_type != ET_EXEC && elf_ex->e_type != ET_DYN)
877 		goto out;
878 	if (!elf_check_arch(elf_ex))
879 		goto out;
880 	if (elf_check_fdpic(elf_ex))
881 		goto out;
882 	if (!bprm->file->f_op->mmap)
883 		goto out;
884 
885 	elf_phdata = load_elf_phdrs(elf_ex, bprm->file);
886 	if (!elf_phdata)
887 		goto out;
888 
889 	elf_ppnt = elf_phdata;
890 	for (i = 0; i < elf_ex->e_phnum; i++, elf_ppnt++) {
891 		char *elf_interpreter;
892 
893 		if (elf_ppnt->p_type == PT_GNU_PROPERTY) {
894 			elf_property_phdata = elf_ppnt;
895 			continue;
896 		}
897 
898 		if (elf_ppnt->p_type != PT_INTERP)
899 			continue;
900 
901 		/*
902 		 * This is the program interpreter used for shared libraries -
903 		 * for now assume that this is an a.out format binary.
904 		 */
905 		retval = -ENOEXEC;
906 		if (elf_ppnt->p_filesz > PATH_MAX || elf_ppnt->p_filesz < 2)
907 			goto out_free_ph;
908 
909 		retval = -ENOMEM;
910 		elf_interpreter = kmalloc(elf_ppnt->p_filesz, GFP_KERNEL);
911 		if (!elf_interpreter)
912 			goto out_free_ph;
913 
914 		retval = elf_read(bprm->file, elf_interpreter, elf_ppnt->p_filesz,
915 				  elf_ppnt->p_offset);
916 		if (retval < 0)
917 			goto out_free_interp;
918 		/* make sure path is NULL terminated */
919 		retval = -ENOEXEC;
920 		if (elf_interpreter[elf_ppnt->p_filesz - 1] != '\0')
921 			goto out_free_interp;
922 
923 		interpreter = open_exec(elf_interpreter);
924 		kfree(elf_interpreter);
925 		retval = PTR_ERR(interpreter);
926 		if (IS_ERR(interpreter))
927 			goto out_free_ph;
928 
929 		/*
930 		 * If the binary is not readable then enforce mm->dumpable = 0
931 		 * regardless of the interpreter's permissions.
932 		 */
933 		would_dump(bprm, interpreter);
934 
935 		interp_elf_ex = kmalloc(sizeof(*interp_elf_ex), GFP_KERNEL);
936 		if (!interp_elf_ex) {
937 			retval = -ENOMEM;
938 			goto out_free_file;
939 		}
940 
941 		/* Get the exec headers */
942 		retval = elf_read(interpreter, interp_elf_ex,
943 				  sizeof(*interp_elf_ex), 0);
944 		if (retval < 0)
945 			goto out_free_dentry;
946 
947 		break;
948 
949 out_free_interp:
950 		kfree(elf_interpreter);
951 		goto out_free_ph;
952 	}
953 
954 	elf_ppnt = elf_phdata;
955 	for (i = 0; i < elf_ex->e_phnum; i++, elf_ppnt++)
956 		switch (elf_ppnt->p_type) {
957 		case PT_GNU_STACK:
958 			if (elf_ppnt->p_flags & PF_X)
959 				executable_stack = EXSTACK_ENABLE_X;
960 			else
961 				executable_stack = EXSTACK_DISABLE_X;
962 			break;
963 
964 		case PT_LOPROC ... PT_HIPROC:
965 			retval = arch_elf_pt_proc(elf_ex, elf_ppnt,
966 						  bprm->file, false,
967 						  &arch_state);
968 			if (retval)
969 				goto out_free_dentry;
970 			break;
971 		}
972 
973 	/* Some simple consistency checks for the interpreter */
974 	if (interpreter) {
975 		retval = -ELIBBAD;
976 		/* Not an ELF interpreter */
977 		if (memcmp(interp_elf_ex->e_ident, ELFMAG, SELFMAG) != 0)
978 			goto out_free_dentry;
979 		/* Verify the interpreter has a valid arch */
980 		if (!elf_check_arch(interp_elf_ex) ||
981 		    elf_check_fdpic(interp_elf_ex))
982 			goto out_free_dentry;
983 
984 		/* Load the interpreter program headers */
985 		interp_elf_phdata = load_elf_phdrs(interp_elf_ex,
986 						   interpreter);
987 		if (!interp_elf_phdata)
988 			goto out_free_dentry;
989 
990 		/* Pass PT_LOPROC..PT_HIPROC headers to arch code */
991 		elf_property_phdata = NULL;
992 		elf_ppnt = interp_elf_phdata;
993 		for (i = 0; i < interp_elf_ex->e_phnum; i++, elf_ppnt++)
994 			switch (elf_ppnt->p_type) {
995 			case PT_GNU_PROPERTY:
996 				elf_property_phdata = elf_ppnt;
997 				break;
998 
999 			case PT_LOPROC ... PT_HIPROC:
1000 				retval = arch_elf_pt_proc(interp_elf_ex,
1001 							  elf_ppnt, interpreter,
1002 							  true, &arch_state);
1003 				if (retval)
1004 					goto out_free_dentry;
1005 				break;
1006 			}
1007 	}
1008 
1009 	retval = parse_elf_properties(interpreter ?: bprm->file,
1010 				      elf_property_phdata, &arch_state);
1011 	if (retval)
1012 		goto out_free_dentry;
1013 
1014 	/*
1015 	 * Allow arch code to reject the ELF at this point, whilst it's
1016 	 * still possible to return an error to the code that invoked
1017 	 * the exec syscall.
1018 	 */
1019 	retval = arch_check_elf(elf_ex,
1020 				!!interpreter, interp_elf_ex,
1021 				&arch_state);
1022 	if (retval)
1023 		goto out_free_dentry;
1024 
1025 	/* Flush all traces of the currently running executable */
1026 	retval = begin_new_exec(bprm);
1027 	if (retval)
1028 		goto out_free_dentry;
1029 
1030 	/* Do this immediately, since STACK_TOP as used in setup_arg_pages
1031 	   may depend on the personality.  */
1032 	SET_PERSONALITY2(*elf_ex, &arch_state);
1033 	if (elf_read_implies_exec(*elf_ex, executable_stack))
1034 		current->personality |= READ_IMPLIES_EXEC;
1035 
1036 	if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space)
1037 		current->flags |= PF_RANDOMIZE;
1038 
1039 	setup_new_exec(bprm);
1040 
1041 	/* Do this so that we can load the interpreter, if need be.  We will
1042 	   change some of these later */
1043 	retval = setup_arg_pages(bprm, randomize_stack_top(STACK_TOP),
1044 				 executable_stack);
1045 	if (retval < 0)
1046 		goto out_free_dentry;
1047 
1048 	elf_brk = 0;
1049 
1050 	start_code = ~0UL;
1051 	end_code = 0;
1052 	start_data = 0;
1053 	end_data = 0;
1054 
1055 	/* Now we do a little grungy work by mmapping the ELF image into
1056 	   the correct location in memory. */
1057 	for(i = 0, elf_ppnt = elf_phdata;
1058 	    i < elf_ex->e_phnum; i++, elf_ppnt++) {
1059 		int elf_prot, elf_flags;
1060 		unsigned long k, vaddr;
1061 		unsigned long total_size = 0;
1062 		unsigned long alignment;
1063 
1064 		if (elf_ppnt->p_type != PT_LOAD)
1065 			continue;
1066 
1067 		elf_prot = make_prot(elf_ppnt->p_flags, &arch_state,
1068 				     !!interpreter, false);
1069 
1070 		elf_flags = MAP_PRIVATE;
1071 
1072 		vaddr = elf_ppnt->p_vaddr;
1073 		/*
1074 		 * The first time through the loop, first_pt_load is true:
1075 		 * layout will be calculated. Once set, use MAP_FIXED since
1076 		 * we know we've already safely mapped the entire region with
1077 		 * MAP_FIXED_NOREPLACE in the once-per-binary logic following.
1078 		 */
1079 		if (!first_pt_load) {
1080 			elf_flags |= MAP_FIXED;
1081 		} else if (elf_ex->e_type == ET_EXEC) {
1082 			/*
1083 			 * This logic is run once for the first LOAD Program
1084 			 * Header for ET_EXEC binaries. No special handling
1085 			 * is needed.
1086 			 */
1087 			elf_flags |= MAP_FIXED_NOREPLACE;
1088 		} else if (elf_ex->e_type == ET_DYN) {
1089 			/*
1090 			 * This logic is run once for the first LOAD Program
1091 			 * Header for ET_DYN binaries to calculate the
1092 			 * randomization (load_bias) for all the LOAD
1093 			 * Program Headers.
1094 			 *
1095 			 * There are effectively two types of ET_DYN
1096 			 * binaries: programs (i.e. PIE: ET_DYN with INTERP)
1097 			 * and loaders (ET_DYN without INTERP, since they
1098 			 * _are_ the ELF interpreter). The loaders must
1099 			 * be loaded away from programs since the program
1100 			 * may otherwise collide with the loader (especially
1101 			 * for ET_EXEC which does not have a randomized
1102 			 * position). For example to handle invocations of
1103 			 * "./ld.so someprog" to test out a new version of
1104 			 * the loader, the subsequent program that the
1105 			 * loader loads must avoid the loader itself, so
1106 			 * they cannot share the same load range. Sufficient
1107 			 * room for the brk must be allocated with the
1108 			 * loader as well, since brk must be available with
1109 			 * the loader.
1110 			 *
1111 			 * Therefore, programs are loaded offset from
1112 			 * ELF_ET_DYN_BASE and loaders are loaded into the
1113 			 * independently randomized mmap region (0 load_bias
1114 			 * without MAP_FIXED nor MAP_FIXED_NOREPLACE).
1115 			 */
1116 			if (interpreter) {
1117 				load_bias = ELF_ET_DYN_BASE;
1118 				if (current->flags & PF_RANDOMIZE)
1119 					load_bias += arch_mmap_rnd();
1120 				alignment = maximum_alignment(elf_phdata, elf_ex->e_phnum);
1121 				if (alignment)
1122 					load_bias &= ~(alignment - 1);
1123 				elf_flags |= MAP_FIXED_NOREPLACE;
1124 			} else
1125 				load_bias = 0;
1126 
1127 			/*
1128 			 * Since load_bias is used for all subsequent loading
1129 			 * calculations, we must lower it by the first vaddr
1130 			 * so that the remaining calculations based on the
1131 			 * ELF vaddrs will be correctly offset. The result
1132 			 * is then page aligned.
1133 			 */
1134 			load_bias = ELF_PAGESTART(load_bias - vaddr);
1135 
1136 			/*
1137 			 * Calculate the entire size of the ELF mapping
1138 			 * (total_size), used for the initial mapping,
1139 			 * due to load_addr_set which is set to true later
1140 			 * once the initial mapping is performed.
1141 			 *
1142 			 * Note that this is only sensible when the LOAD
1143 			 * segments are contiguous (or overlapping). If
1144 			 * used for LOADs that are far apart, this would
1145 			 * cause the holes between LOADs to be mapped,
1146 			 * running the risk of having the mapping fail,
1147 			 * as it would be larger than the ELF file itself.
1148 			 *
1149 			 * As a result, only ET_DYN does this, since
1150 			 * some ET_EXEC (e.g. ia64) may have large virtual
1151 			 * memory holes between LOADs.
1152 			 *
1153 			 */
1154 			total_size = total_mapping_size(elf_phdata,
1155 							elf_ex->e_phnum);
1156 			if (!total_size) {
1157 				retval = -EINVAL;
1158 				goto out_free_dentry;
1159 			}
1160 		}
1161 
1162 		error = elf_load(bprm->file, load_bias + vaddr, elf_ppnt,
1163 				elf_prot, elf_flags, total_size);
1164 		if (BAD_ADDR(error)) {
1165 			retval = IS_ERR_VALUE(error) ?
1166 				PTR_ERR((void*)error) : -EINVAL;
1167 			goto out_free_dentry;
1168 		}
1169 
1170 		if (first_pt_load) {
1171 			first_pt_load = 0;
1172 			if (elf_ex->e_type == ET_DYN) {
1173 				load_bias += error -
1174 				             ELF_PAGESTART(load_bias + vaddr);
1175 				reloc_func_desc = load_bias;
1176 			}
1177 		}
1178 
1179 		/*
1180 		 * Figure out which segment in the file contains the Program
1181 		 * Header table, and map to the associated memory address.
1182 		 */
1183 		if (elf_ppnt->p_offset <= elf_ex->e_phoff &&
1184 		    elf_ex->e_phoff < elf_ppnt->p_offset + elf_ppnt->p_filesz) {
1185 			phdr_addr = elf_ex->e_phoff - elf_ppnt->p_offset +
1186 				    elf_ppnt->p_vaddr;
1187 		}
1188 
1189 		k = elf_ppnt->p_vaddr;
1190 		if ((elf_ppnt->p_flags & PF_X) && k < start_code)
1191 			start_code = k;
1192 		if (start_data < k)
1193 			start_data = k;
1194 
1195 		/*
1196 		 * Check to see if the section's size will overflow the
1197 		 * allowed task size. Note that p_filesz must always be
1198 		 * <= p_memsz so it is only necessary to check p_memsz.
1199 		 */
1200 		if (BAD_ADDR(k) || elf_ppnt->p_filesz > elf_ppnt->p_memsz ||
1201 		    elf_ppnt->p_memsz > TASK_SIZE ||
1202 		    TASK_SIZE - elf_ppnt->p_memsz < k) {
1203 			/* set_brk can never work. Avoid overflows. */
1204 			retval = -EINVAL;
1205 			goto out_free_dentry;
1206 		}
1207 
1208 		k = elf_ppnt->p_vaddr + elf_ppnt->p_filesz;
1209 
1210 		if ((elf_ppnt->p_flags & PF_X) && end_code < k)
1211 			end_code = k;
1212 		if (end_data < k)
1213 			end_data = k;
1214 		k = elf_ppnt->p_vaddr + elf_ppnt->p_memsz;
1215 		if (k > elf_brk)
1216 			elf_brk = k;
1217 	}
1218 
1219 	e_entry = elf_ex->e_entry + load_bias;
1220 	phdr_addr += load_bias;
1221 	elf_brk += load_bias;
1222 	start_code += load_bias;
1223 	end_code += load_bias;
1224 	start_data += load_bias;
1225 	end_data += load_bias;
1226 
1227 	current->mm->start_brk = current->mm->brk = ELF_PAGEALIGN(elf_brk);
1228 
1229 	if (interpreter) {
1230 		elf_entry = load_elf_interp(interp_elf_ex,
1231 					    interpreter,
1232 					    load_bias, interp_elf_phdata,
1233 					    &arch_state);
1234 		if (!IS_ERR_VALUE(elf_entry)) {
1235 			/*
1236 			 * load_elf_interp() returns relocation
1237 			 * adjustment
1238 			 */
1239 			interp_load_addr = elf_entry;
1240 			elf_entry += interp_elf_ex->e_entry;
1241 		}
1242 		if (BAD_ADDR(elf_entry)) {
1243 			retval = IS_ERR_VALUE(elf_entry) ?
1244 					(int)elf_entry : -EINVAL;
1245 			goto out_free_dentry;
1246 		}
1247 		reloc_func_desc = interp_load_addr;
1248 
1249 		allow_write_access(interpreter);
1250 		fput(interpreter);
1251 
1252 		kfree(interp_elf_ex);
1253 		kfree(interp_elf_phdata);
1254 	} else {
1255 		elf_entry = e_entry;
1256 		if (BAD_ADDR(elf_entry)) {
1257 			retval = -EINVAL;
1258 			goto out_free_dentry;
1259 		}
1260 	}
1261 
1262 	kfree(elf_phdata);
1263 
1264 	set_binfmt(&elf_format);
1265 
1266 #ifdef ARCH_HAS_SETUP_ADDITIONAL_PAGES
1267 	retval = ARCH_SETUP_ADDITIONAL_PAGES(bprm, elf_ex, !!interpreter);
1268 	if (retval < 0)
1269 		goto out;
1270 #endif /* ARCH_HAS_SETUP_ADDITIONAL_PAGES */
1271 
1272 	retval = create_elf_tables(bprm, elf_ex, interp_load_addr,
1273 				   e_entry, phdr_addr);
1274 	if (retval < 0)
1275 		goto out;
1276 
1277 	mm = current->mm;
1278 	mm->end_code = end_code;
1279 	mm->start_code = start_code;
1280 	mm->start_data = start_data;
1281 	mm->end_data = end_data;
1282 	mm->start_stack = bprm->p;
1283 
1284 	if ((current->flags & PF_RANDOMIZE) && (randomize_va_space > 1)) {
1285 		/*
1286 		 * For architectures with ELF randomization, when executing
1287 		 * a loader directly (i.e. no interpreter listed in ELF
1288 		 * headers), move the brk area out of the mmap region
1289 		 * (since it grows up, and may collide early with the stack
1290 		 * growing down), and into the unused ELF_ET_DYN_BASE region.
1291 		 */
1292 		if (IS_ENABLED(CONFIG_ARCH_HAS_ELF_RANDOMIZE) &&
1293 		    elf_ex->e_type == ET_DYN && !interpreter) {
1294 			mm->brk = mm->start_brk = ELF_ET_DYN_BASE;
1295 		}
1296 
1297 		mm->brk = mm->start_brk = arch_randomize_brk(mm);
1298 #ifdef compat_brk_randomized
1299 		current->brk_randomized = 1;
1300 #endif
1301 	}
1302 
1303 	if (current->personality & MMAP_PAGE_ZERO) {
1304 		/* Why this, you ask???  Well SVr4 maps page 0 as read-only,
1305 		   and some applications "depend" upon this behavior.
1306 		   Since we do not have the power to recompile these, we
1307 		   emulate the SVr4 behavior. Sigh. */
1308 		error = vm_mmap(NULL, 0, PAGE_SIZE, PROT_READ | PROT_EXEC,
1309 				MAP_FIXED | MAP_PRIVATE, 0);
1310 	}
1311 
1312 	regs = current_pt_regs();
1313 #ifdef ELF_PLAT_INIT
1314 	/*
1315 	 * The ABI may specify that certain registers be set up in special
1316 	 * ways (on i386 %edx is the address of a DT_FINI function, for
1317 	 * example.  In addition, it may also specify (eg, PowerPC64 ELF)
1318 	 * that the e_entry field is the address of the function descriptor
1319 	 * for the startup routine, rather than the address of the startup
1320 	 * routine itself.  This macro performs whatever initialization to
1321 	 * the regs structure is required as well as any relocations to the
1322 	 * function descriptor entries when executing dynamically links apps.
1323 	 */
1324 	ELF_PLAT_INIT(regs, reloc_func_desc);
1325 #endif
1326 
1327 	finalize_exec(bprm);
1328 	START_THREAD(elf_ex, regs, elf_entry, bprm->p);
1329 	retval = 0;
1330 out:
1331 	return retval;
1332 
1333 	/* error cleanup */
1334 out_free_dentry:
1335 	kfree(interp_elf_ex);
1336 	kfree(interp_elf_phdata);
1337 out_free_file:
1338 	allow_write_access(interpreter);
1339 	if (interpreter)
1340 		fput(interpreter);
1341 out_free_ph:
1342 	kfree(elf_phdata);
1343 	goto out;
1344 }
1345 
1346 #ifdef CONFIG_USELIB
1347 /* This is really simpleminded and specialized - we are loading an
1348    a.out library that is given an ELF header. */
1349 static int load_elf_library(struct file *file)
1350 {
1351 	struct elf_phdr *elf_phdata;
1352 	struct elf_phdr *eppnt;
1353 	unsigned long elf_bss, bss, len;
1354 	int retval, error, i, j;
1355 	struct elfhdr elf_ex;
1356 
1357 	error = -ENOEXEC;
1358 	retval = elf_read(file, &elf_ex, sizeof(elf_ex), 0);
1359 	if (retval < 0)
1360 		goto out;
1361 
1362 	if (memcmp(elf_ex.e_ident, ELFMAG, SELFMAG) != 0)
1363 		goto out;
1364 
1365 	/* First of all, some simple consistency checks */
1366 	if (elf_ex.e_type != ET_EXEC || elf_ex.e_phnum > 2 ||
1367 	    !elf_check_arch(&elf_ex) || !file->f_op->mmap)
1368 		goto out;
1369 	if (elf_check_fdpic(&elf_ex))
1370 		goto out;
1371 
1372 	/* Now read in all of the header information */
1373 
1374 	j = sizeof(struct elf_phdr) * elf_ex.e_phnum;
1375 	/* j < ELF_MIN_ALIGN because elf_ex.e_phnum <= 2 */
1376 
1377 	error = -ENOMEM;
1378 	elf_phdata = kmalloc(j, GFP_KERNEL);
1379 	if (!elf_phdata)
1380 		goto out;
1381 
1382 	eppnt = elf_phdata;
1383 	error = -ENOEXEC;
1384 	retval = elf_read(file, eppnt, j, elf_ex.e_phoff);
1385 	if (retval < 0)
1386 		goto out_free_ph;
1387 
1388 	for (j = 0, i = 0; i<elf_ex.e_phnum; i++)
1389 		if ((eppnt + i)->p_type == PT_LOAD)
1390 			j++;
1391 	if (j != 1)
1392 		goto out_free_ph;
1393 
1394 	while (eppnt->p_type != PT_LOAD)
1395 		eppnt++;
1396 
1397 	/* Now use mmap to map the library into memory. */
1398 	error = vm_mmap(file,
1399 			ELF_PAGESTART(eppnt->p_vaddr),
1400 			(eppnt->p_filesz +
1401 			 ELF_PAGEOFFSET(eppnt->p_vaddr)),
1402 			PROT_READ | PROT_WRITE | PROT_EXEC,
1403 			MAP_FIXED_NOREPLACE | MAP_PRIVATE,
1404 			(eppnt->p_offset -
1405 			 ELF_PAGEOFFSET(eppnt->p_vaddr)));
1406 	if (error != ELF_PAGESTART(eppnt->p_vaddr))
1407 		goto out_free_ph;
1408 
1409 	elf_bss = eppnt->p_vaddr + eppnt->p_filesz;
1410 	if (padzero(elf_bss)) {
1411 		error = -EFAULT;
1412 		goto out_free_ph;
1413 	}
1414 
1415 	len = ELF_PAGEALIGN(eppnt->p_filesz + eppnt->p_vaddr);
1416 	bss = ELF_PAGEALIGN(eppnt->p_memsz + eppnt->p_vaddr);
1417 	if (bss > len) {
1418 		error = vm_brk(len, bss - len);
1419 		if (error)
1420 			goto out_free_ph;
1421 	}
1422 	error = 0;
1423 
1424 out_free_ph:
1425 	kfree(elf_phdata);
1426 out:
1427 	return error;
1428 }
1429 #endif /* #ifdef CONFIG_USELIB */
1430 
1431 #ifdef CONFIG_ELF_CORE
1432 /*
1433  * ELF core dumper
1434  *
1435  * Modelled on fs/exec.c:aout_core_dump()
1436  * Jeremy Fitzhardinge <[email protected]>
1437  */
1438 
1439 /* An ELF note in memory */
1440 struct memelfnote
1441 {
1442 	const char *name;
1443 	int type;
1444 	unsigned int datasz;
1445 	void *data;
1446 };
1447 
1448 static int notesize(struct memelfnote *en)
1449 {
1450 	int sz;
1451 
1452 	sz = sizeof(struct elf_note);
1453 	sz += roundup(strlen(en->name) + 1, 4);
1454 	sz += roundup(en->datasz, 4);
1455 
1456 	return sz;
1457 }
1458 
1459 static int writenote(struct memelfnote *men, struct coredump_params *cprm)
1460 {
1461 	struct elf_note en;
1462 	en.n_namesz = strlen(men->name) + 1;
1463 	en.n_descsz = men->datasz;
1464 	en.n_type = men->type;
1465 
1466 	return dump_emit(cprm, &en, sizeof(en)) &&
1467 	    dump_emit(cprm, men->name, en.n_namesz) && dump_align(cprm, 4) &&
1468 	    dump_emit(cprm, men->data, men->datasz) && dump_align(cprm, 4);
1469 }
1470 
1471 static void fill_elf_header(struct elfhdr *elf, int segs,
1472 			    u16 machine, u32 flags)
1473 {
1474 	memset(elf, 0, sizeof(*elf));
1475 
1476 	memcpy(elf->e_ident, ELFMAG, SELFMAG);
1477 	elf->e_ident[EI_CLASS] = ELF_CLASS;
1478 	elf->e_ident[EI_DATA] = ELF_DATA;
1479 	elf->e_ident[EI_VERSION] = EV_CURRENT;
1480 	elf->e_ident[EI_OSABI] = ELF_OSABI;
1481 
1482 	elf->e_type = ET_CORE;
1483 	elf->e_machine = machine;
1484 	elf->e_version = EV_CURRENT;
1485 	elf->e_phoff = sizeof(struct elfhdr);
1486 	elf->e_flags = flags;
1487 	elf->e_ehsize = sizeof(struct elfhdr);
1488 	elf->e_phentsize = sizeof(struct elf_phdr);
1489 	elf->e_phnum = segs;
1490 }
1491 
1492 static void fill_elf_note_phdr(struct elf_phdr *phdr, int sz, loff_t offset)
1493 {
1494 	phdr->p_type = PT_NOTE;
1495 	phdr->p_offset = offset;
1496 	phdr->p_vaddr = 0;
1497 	phdr->p_paddr = 0;
1498 	phdr->p_filesz = sz;
1499 	phdr->p_memsz = 0;
1500 	phdr->p_flags = 0;
1501 	phdr->p_align = 4;
1502 }
1503 
1504 static void fill_note(struct memelfnote *note, const char *name, int type,
1505 		unsigned int sz, void *data)
1506 {
1507 	note->name = name;
1508 	note->type = type;
1509 	note->datasz = sz;
1510 	note->data = data;
1511 }
1512 
1513 /*
1514  * fill up all the fields in prstatus from the given task struct, except
1515  * registers which need to be filled up separately.
1516  */
1517 static void fill_prstatus(struct elf_prstatus_common *prstatus,
1518 		struct task_struct *p, long signr)
1519 {
1520 	prstatus->pr_info.si_signo = prstatus->pr_cursig = signr;
1521 	prstatus->pr_sigpend = p->pending.signal.sig[0];
1522 	prstatus->pr_sighold = p->blocked.sig[0];
1523 	rcu_read_lock();
1524 	prstatus->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
1525 	rcu_read_unlock();
1526 	prstatus->pr_pid = task_pid_vnr(p);
1527 	prstatus->pr_pgrp = task_pgrp_vnr(p);
1528 	prstatus->pr_sid = task_session_vnr(p);
1529 	if (thread_group_leader(p)) {
1530 		struct task_cputime cputime;
1531 
1532 		/*
1533 		 * This is the record for the group leader.  It shows the
1534 		 * group-wide total, not its individual thread total.
1535 		 */
1536 		thread_group_cputime(p, &cputime);
1537 		prstatus->pr_utime = ns_to_kernel_old_timeval(cputime.utime);
1538 		prstatus->pr_stime = ns_to_kernel_old_timeval(cputime.stime);
1539 	} else {
1540 		u64 utime, stime;
1541 
1542 		task_cputime(p, &utime, &stime);
1543 		prstatus->pr_utime = ns_to_kernel_old_timeval(utime);
1544 		prstatus->pr_stime = ns_to_kernel_old_timeval(stime);
1545 	}
1546 
1547 	prstatus->pr_cutime = ns_to_kernel_old_timeval(p->signal->cutime);
1548 	prstatus->pr_cstime = ns_to_kernel_old_timeval(p->signal->cstime);
1549 }
1550 
1551 static int fill_psinfo(struct elf_prpsinfo *psinfo, struct task_struct *p,
1552 		       struct mm_struct *mm)
1553 {
1554 	const struct cred *cred;
1555 	unsigned int i, len;
1556 	unsigned int state;
1557 
1558 	/* first copy the parameters from user space */
1559 	memset(psinfo, 0, sizeof(struct elf_prpsinfo));
1560 
1561 	len = mm->arg_end - mm->arg_start;
1562 	if (len >= ELF_PRARGSZ)
1563 		len = ELF_PRARGSZ-1;
1564 	if (copy_from_user(&psinfo->pr_psargs,
1565 		           (const char __user *)mm->arg_start, len))
1566 		return -EFAULT;
1567 	for(i = 0; i < len; i++)
1568 		if (psinfo->pr_psargs[i] == 0)
1569 			psinfo->pr_psargs[i] = ' ';
1570 	psinfo->pr_psargs[len] = 0;
1571 
1572 	rcu_read_lock();
1573 	psinfo->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
1574 	rcu_read_unlock();
1575 	psinfo->pr_pid = task_pid_vnr(p);
1576 	psinfo->pr_pgrp = task_pgrp_vnr(p);
1577 	psinfo->pr_sid = task_session_vnr(p);
1578 
1579 	state = READ_ONCE(p->__state);
1580 	i = state ? ffz(~state) + 1 : 0;
1581 	psinfo->pr_state = i;
1582 	psinfo->pr_sname = (i > 5) ? '.' : "RSDTZW"[i];
1583 	psinfo->pr_zomb = psinfo->pr_sname == 'Z';
1584 	psinfo->pr_nice = task_nice(p);
1585 	psinfo->pr_flag = p->flags;
1586 	rcu_read_lock();
1587 	cred = __task_cred(p);
1588 	SET_UID(psinfo->pr_uid, from_kuid_munged(cred->user_ns, cred->uid));
1589 	SET_GID(psinfo->pr_gid, from_kgid_munged(cred->user_ns, cred->gid));
1590 	rcu_read_unlock();
1591 	get_task_comm(psinfo->pr_fname, p);
1592 
1593 	return 0;
1594 }
1595 
1596 static void fill_auxv_note(struct memelfnote *note, struct mm_struct *mm)
1597 {
1598 	elf_addr_t *auxv = (elf_addr_t *) mm->saved_auxv;
1599 	int i = 0;
1600 	do
1601 		i += 2;
1602 	while (auxv[i - 2] != AT_NULL);
1603 	fill_note(note, "CORE", NT_AUXV, i * sizeof(elf_addr_t), auxv);
1604 }
1605 
1606 static void fill_siginfo_note(struct memelfnote *note, user_siginfo_t *csigdata,
1607 		const kernel_siginfo_t *siginfo)
1608 {
1609 	copy_siginfo_to_external(csigdata, siginfo);
1610 	fill_note(note, "CORE", NT_SIGINFO, sizeof(*csigdata), csigdata);
1611 }
1612 
1613 #define MAX_FILE_NOTE_SIZE (4*1024*1024)
1614 /*
1615  * Format of NT_FILE note:
1616  *
1617  * long count     -- how many files are mapped
1618  * long page_size -- units for file_ofs
1619  * array of [COUNT] elements of
1620  *   long start
1621  *   long end
1622  *   long file_ofs
1623  * followed by COUNT filenames in ASCII: "FILE1" NUL "FILE2" NUL...
1624  */
1625 static int fill_files_note(struct memelfnote *note, struct coredump_params *cprm)
1626 {
1627 	unsigned count, size, names_ofs, remaining, n;
1628 	user_long_t *data;
1629 	user_long_t *start_end_ofs;
1630 	char *name_base, *name_curpos;
1631 	int i;
1632 
1633 	/* *Estimated* file count and total data size needed */
1634 	count = cprm->vma_count;
1635 	if (count > UINT_MAX / 64)
1636 		return -EINVAL;
1637 	size = count * 64;
1638 
1639 	names_ofs = (2 + 3 * count) * sizeof(data[0]);
1640  alloc:
1641 	if (size >= MAX_FILE_NOTE_SIZE) /* paranoia check */
1642 		return -EINVAL;
1643 	size = round_up(size, PAGE_SIZE);
1644 	/*
1645 	 * "size" can be 0 here legitimately.
1646 	 * Let it ENOMEM and omit NT_FILE section which will be empty anyway.
1647 	 */
1648 	data = kvmalloc(size, GFP_KERNEL);
1649 	if (ZERO_OR_NULL_PTR(data))
1650 		return -ENOMEM;
1651 
1652 	start_end_ofs = data + 2;
1653 	name_base = name_curpos = ((char *)data) + names_ofs;
1654 	remaining = size - names_ofs;
1655 	count = 0;
1656 	for (i = 0; i < cprm->vma_count; i++) {
1657 		struct core_vma_metadata *m = &cprm->vma_meta[i];
1658 		struct file *file;
1659 		const char *filename;
1660 
1661 		file = m->file;
1662 		if (!file)
1663 			continue;
1664 		filename = file_path(file, name_curpos, remaining);
1665 		if (IS_ERR(filename)) {
1666 			if (PTR_ERR(filename) == -ENAMETOOLONG) {
1667 				kvfree(data);
1668 				size = size * 5 / 4;
1669 				goto alloc;
1670 			}
1671 			continue;
1672 		}
1673 
1674 		/* file_path() fills at the end, move name down */
1675 		/* n = strlen(filename) + 1: */
1676 		n = (name_curpos + remaining) - filename;
1677 		remaining = filename - name_curpos;
1678 		memmove(name_curpos, filename, n);
1679 		name_curpos += n;
1680 
1681 		*start_end_ofs++ = m->start;
1682 		*start_end_ofs++ = m->end;
1683 		*start_end_ofs++ = m->pgoff;
1684 		count++;
1685 	}
1686 
1687 	/* Now we know exact count of files, can store it */
1688 	data[0] = count;
1689 	data[1] = PAGE_SIZE;
1690 	/*
1691 	 * Count usually is less than mm->map_count,
1692 	 * we need to move filenames down.
1693 	 */
1694 	n = cprm->vma_count - count;
1695 	if (n != 0) {
1696 		unsigned shift_bytes = n * 3 * sizeof(data[0]);
1697 		memmove(name_base - shift_bytes, name_base,
1698 			name_curpos - name_base);
1699 		name_curpos -= shift_bytes;
1700 	}
1701 
1702 	size = name_curpos - (char *)data;
1703 	fill_note(note, "CORE", NT_FILE, size, data);
1704 	return 0;
1705 }
1706 
1707 #include <linux/regset.h>
1708 
1709 struct elf_thread_core_info {
1710 	struct elf_thread_core_info *next;
1711 	struct task_struct *task;
1712 	struct elf_prstatus prstatus;
1713 	struct memelfnote notes[];
1714 };
1715 
1716 struct elf_note_info {
1717 	struct elf_thread_core_info *thread;
1718 	struct memelfnote psinfo;
1719 	struct memelfnote signote;
1720 	struct memelfnote auxv;
1721 	struct memelfnote files;
1722 	user_siginfo_t csigdata;
1723 	size_t size;
1724 	int thread_notes;
1725 };
1726 
1727 #ifdef CORE_DUMP_USE_REGSET
1728 /*
1729  * When a regset has a writeback hook, we call it on each thread before
1730  * dumping user memory.  On register window machines, this makes sure the
1731  * user memory backing the register data is up to date before we read it.
1732  */
1733 static void do_thread_regset_writeback(struct task_struct *task,
1734 				       const struct user_regset *regset)
1735 {
1736 	if (regset->writeback)
1737 		regset->writeback(task, regset, 1);
1738 }
1739 
1740 #ifndef PRSTATUS_SIZE
1741 #define PRSTATUS_SIZE sizeof(struct elf_prstatus)
1742 #endif
1743 
1744 #ifndef SET_PR_FPVALID
1745 #define SET_PR_FPVALID(S) ((S)->pr_fpvalid = 1)
1746 #endif
1747 
1748 static int fill_thread_core_info(struct elf_thread_core_info *t,
1749 				 const struct user_regset_view *view,
1750 				 long signr, struct elf_note_info *info)
1751 {
1752 	unsigned int note_iter, view_iter;
1753 
1754 	/*
1755 	 * NT_PRSTATUS is the one special case, because the regset data
1756 	 * goes into the pr_reg field inside the note contents, rather
1757 	 * than being the whole note contents.  We fill the regset in here.
1758 	 * We assume that regset 0 is NT_PRSTATUS.
1759 	 */
1760 	fill_prstatus(&t->prstatus.common, t->task, signr);
1761 	regset_get(t->task, &view->regsets[0],
1762 		   sizeof(t->prstatus.pr_reg), &t->prstatus.pr_reg);
1763 
1764 	fill_note(&t->notes[0], "CORE", NT_PRSTATUS,
1765 		  PRSTATUS_SIZE, &t->prstatus);
1766 	info->size += notesize(&t->notes[0]);
1767 
1768 	do_thread_regset_writeback(t->task, &view->regsets[0]);
1769 
1770 	/*
1771 	 * Each other regset might generate a note too.  For each regset
1772 	 * that has no core_note_type or is inactive, skip it.
1773 	 */
1774 	note_iter = 1;
1775 	for (view_iter = 1; view_iter < view->n; ++view_iter) {
1776 		const struct user_regset *regset = &view->regsets[view_iter];
1777 		int note_type = regset->core_note_type;
1778 		bool is_fpreg = note_type == NT_PRFPREG;
1779 		void *data;
1780 		int ret;
1781 
1782 		do_thread_regset_writeback(t->task, regset);
1783 		if (!note_type) // not for coredumps
1784 			continue;
1785 		if (regset->active && regset->active(t->task, regset) <= 0)
1786 			continue;
1787 
1788 		ret = regset_get_alloc(t->task, regset, ~0U, &data);
1789 		if (ret < 0)
1790 			continue;
1791 
1792 		if (WARN_ON_ONCE(note_iter >= info->thread_notes))
1793 			break;
1794 
1795 		if (is_fpreg)
1796 			SET_PR_FPVALID(&t->prstatus);
1797 
1798 		fill_note(&t->notes[note_iter], is_fpreg ? "CORE" : "LINUX",
1799 			  note_type, ret, data);
1800 
1801 		info->size += notesize(&t->notes[note_iter]);
1802 		note_iter++;
1803 	}
1804 
1805 	return 1;
1806 }
1807 #else
1808 static int fill_thread_core_info(struct elf_thread_core_info *t,
1809 				 const struct user_regset_view *view,
1810 				 long signr, struct elf_note_info *info)
1811 {
1812 	struct task_struct *p = t->task;
1813 	elf_fpregset_t *fpu;
1814 
1815 	fill_prstatus(&t->prstatus.common, p, signr);
1816 	elf_core_copy_task_regs(p, &t->prstatus.pr_reg);
1817 
1818 	fill_note(&t->notes[0], "CORE", NT_PRSTATUS, sizeof(t->prstatus),
1819 		  &(t->prstatus));
1820 	info->size += notesize(&t->notes[0]);
1821 
1822 	fpu = kzalloc(sizeof(elf_fpregset_t), GFP_KERNEL);
1823 	if (!fpu || !elf_core_copy_task_fpregs(p, fpu)) {
1824 		kfree(fpu);
1825 		return 1;
1826 	}
1827 
1828 	t->prstatus.pr_fpvalid = 1;
1829 	fill_note(&t->notes[1], "CORE", NT_PRFPREG, sizeof(*fpu), fpu);
1830 	info->size += notesize(&t->notes[1]);
1831 
1832 	return 1;
1833 }
1834 #endif
1835 
1836 static int fill_note_info(struct elfhdr *elf, int phdrs,
1837 			  struct elf_note_info *info,
1838 			  struct coredump_params *cprm)
1839 {
1840 	struct task_struct *dump_task = current;
1841 	const struct user_regset_view *view;
1842 	struct elf_thread_core_info *t;
1843 	struct elf_prpsinfo *psinfo;
1844 	struct core_thread *ct;
1845 
1846 	psinfo = kmalloc(sizeof(*psinfo), GFP_KERNEL);
1847 	if (!psinfo)
1848 		return 0;
1849 	fill_note(&info->psinfo, "CORE", NT_PRPSINFO, sizeof(*psinfo), psinfo);
1850 
1851 #ifdef CORE_DUMP_USE_REGSET
1852 	view = task_user_regset_view(dump_task);
1853 
1854 	/*
1855 	 * Figure out how many notes we're going to need for each thread.
1856 	 */
1857 	info->thread_notes = 0;
1858 	for (int i = 0; i < view->n; ++i)
1859 		if (view->regsets[i].core_note_type != 0)
1860 			++info->thread_notes;
1861 
1862 	/*
1863 	 * Sanity check.  We rely on regset 0 being in NT_PRSTATUS,
1864 	 * since it is our one special case.
1865 	 */
1866 	if (unlikely(info->thread_notes == 0) ||
1867 	    unlikely(view->regsets[0].core_note_type != NT_PRSTATUS)) {
1868 		WARN_ON(1);
1869 		return 0;
1870 	}
1871 
1872 	/*
1873 	 * Initialize the ELF file header.
1874 	 */
1875 	fill_elf_header(elf, phdrs,
1876 			view->e_machine, view->e_flags);
1877 #else
1878 	view = NULL;
1879 	info->thread_notes = 2;
1880 	fill_elf_header(elf, phdrs, ELF_ARCH, ELF_CORE_EFLAGS);
1881 #endif
1882 
1883 	/*
1884 	 * Allocate a structure for each thread.
1885 	 */
1886 	info->thread = kzalloc(offsetof(struct elf_thread_core_info,
1887 				     notes[info->thread_notes]),
1888 			    GFP_KERNEL);
1889 	if (unlikely(!info->thread))
1890 		return 0;
1891 
1892 	info->thread->task = dump_task;
1893 	for (ct = dump_task->signal->core_state->dumper.next; ct; ct = ct->next) {
1894 		t = kzalloc(offsetof(struct elf_thread_core_info,
1895 				     notes[info->thread_notes]),
1896 			    GFP_KERNEL);
1897 		if (unlikely(!t))
1898 			return 0;
1899 
1900 		t->task = ct->task;
1901 		t->next = info->thread->next;
1902 		info->thread->next = t;
1903 	}
1904 
1905 	/*
1906 	 * Now fill in each thread's information.
1907 	 */
1908 	for (t = info->thread; t != NULL; t = t->next)
1909 		if (!fill_thread_core_info(t, view, cprm->siginfo->si_signo, info))
1910 			return 0;
1911 
1912 	/*
1913 	 * Fill in the two process-wide notes.
1914 	 */
1915 	fill_psinfo(psinfo, dump_task->group_leader, dump_task->mm);
1916 	info->size += notesize(&info->psinfo);
1917 
1918 	fill_siginfo_note(&info->signote, &info->csigdata, cprm->siginfo);
1919 	info->size += notesize(&info->signote);
1920 
1921 	fill_auxv_note(&info->auxv, current->mm);
1922 	info->size += notesize(&info->auxv);
1923 
1924 	if (fill_files_note(&info->files, cprm) == 0)
1925 		info->size += notesize(&info->files);
1926 
1927 	return 1;
1928 }
1929 
1930 /*
1931  * Write all the notes for each thread.  When writing the first thread, the
1932  * process-wide notes are interleaved after the first thread-specific note.
1933  */
1934 static int write_note_info(struct elf_note_info *info,
1935 			   struct coredump_params *cprm)
1936 {
1937 	bool first = true;
1938 	struct elf_thread_core_info *t = info->thread;
1939 
1940 	do {
1941 		int i;
1942 
1943 		if (!writenote(&t->notes[0], cprm))
1944 			return 0;
1945 
1946 		if (first && !writenote(&info->psinfo, cprm))
1947 			return 0;
1948 		if (first && !writenote(&info->signote, cprm))
1949 			return 0;
1950 		if (first && !writenote(&info->auxv, cprm))
1951 			return 0;
1952 		if (first && info->files.data &&
1953 				!writenote(&info->files, cprm))
1954 			return 0;
1955 
1956 		for (i = 1; i < info->thread_notes; ++i)
1957 			if (t->notes[i].data &&
1958 			    !writenote(&t->notes[i], cprm))
1959 				return 0;
1960 
1961 		first = false;
1962 		t = t->next;
1963 	} while (t);
1964 
1965 	return 1;
1966 }
1967 
1968 static void free_note_info(struct elf_note_info *info)
1969 {
1970 	struct elf_thread_core_info *threads = info->thread;
1971 	while (threads) {
1972 		unsigned int i;
1973 		struct elf_thread_core_info *t = threads;
1974 		threads = t->next;
1975 		WARN_ON(t->notes[0].data && t->notes[0].data != &t->prstatus);
1976 		for (i = 1; i < info->thread_notes; ++i)
1977 			kfree(t->notes[i].data);
1978 		kfree(t);
1979 	}
1980 	kfree(info->psinfo.data);
1981 	kvfree(info->files.data);
1982 }
1983 
1984 static void fill_extnum_info(struct elfhdr *elf, struct elf_shdr *shdr4extnum,
1985 			     elf_addr_t e_shoff, int segs)
1986 {
1987 	elf->e_shoff = e_shoff;
1988 	elf->e_shentsize = sizeof(*shdr4extnum);
1989 	elf->e_shnum = 1;
1990 	elf->e_shstrndx = SHN_UNDEF;
1991 
1992 	memset(shdr4extnum, 0, sizeof(*shdr4extnum));
1993 
1994 	shdr4extnum->sh_type = SHT_NULL;
1995 	shdr4extnum->sh_size = elf->e_shnum;
1996 	shdr4extnum->sh_link = elf->e_shstrndx;
1997 	shdr4extnum->sh_info = segs;
1998 }
1999 
2000 /*
2001  * Actual dumper
2002  *
2003  * This is a two-pass process; first we find the offsets of the bits,
2004  * and then they are actually written out.  If we run out of core limit
2005  * we just truncate.
2006  */
2007 static int elf_core_dump(struct coredump_params *cprm)
2008 {
2009 	int has_dumped = 0;
2010 	int segs, i;
2011 	struct elfhdr elf;
2012 	loff_t offset = 0, dataoff;
2013 	struct elf_note_info info = { };
2014 	struct elf_phdr *phdr4note = NULL;
2015 	struct elf_shdr *shdr4extnum = NULL;
2016 	Elf_Half e_phnum;
2017 	elf_addr_t e_shoff;
2018 
2019 	/*
2020 	 * The number of segs are recored into ELF header as 16bit value.
2021 	 * Please check DEFAULT_MAX_MAP_COUNT definition when you modify here.
2022 	 */
2023 	segs = cprm->vma_count + elf_core_extra_phdrs(cprm);
2024 
2025 	/* for notes section */
2026 	segs++;
2027 
2028 	/* If segs > PN_XNUM(0xffff), then e_phnum overflows. To avoid
2029 	 * this, kernel supports extended numbering. Have a look at
2030 	 * include/linux/elf.h for further information. */
2031 	e_phnum = segs > PN_XNUM ? PN_XNUM : segs;
2032 
2033 	/*
2034 	 * Collect all the non-memory information about the process for the
2035 	 * notes.  This also sets up the file header.
2036 	 */
2037 	if (!fill_note_info(&elf, e_phnum, &info, cprm))
2038 		goto end_coredump;
2039 
2040 	has_dumped = 1;
2041 
2042 	offset += sizeof(elf);				/* ELF header */
2043 	offset += segs * sizeof(struct elf_phdr);	/* Program headers */
2044 
2045 	/* Write notes phdr entry */
2046 	{
2047 		size_t sz = info.size;
2048 
2049 		/* For cell spufs */
2050 		sz += elf_coredump_extra_notes_size();
2051 
2052 		phdr4note = kmalloc(sizeof(*phdr4note), GFP_KERNEL);
2053 		if (!phdr4note)
2054 			goto end_coredump;
2055 
2056 		fill_elf_note_phdr(phdr4note, sz, offset);
2057 		offset += sz;
2058 	}
2059 
2060 	dataoff = offset = roundup(offset, ELF_EXEC_PAGESIZE);
2061 
2062 	offset += cprm->vma_data_size;
2063 	offset += elf_core_extra_data_size(cprm);
2064 	e_shoff = offset;
2065 
2066 	if (e_phnum == PN_XNUM) {
2067 		shdr4extnum = kmalloc(sizeof(*shdr4extnum), GFP_KERNEL);
2068 		if (!shdr4extnum)
2069 			goto end_coredump;
2070 		fill_extnum_info(&elf, shdr4extnum, e_shoff, segs);
2071 	}
2072 
2073 	offset = dataoff;
2074 
2075 	if (!dump_emit(cprm, &elf, sizeof(elf)))
2076 		goto end_coredump;
2077 
2078 	if (!dump_emit(cprm, phdr4note, sizeof(*phdr4note)))
2079 		goto end_coredump;
2080 
2081 	/* Write program headers for segments dump */
2082 	for (i = 0; i < cprm->vma_count; i++) {
2083 		struct core_vma_metadata *meta = cprm->vma_meta + i;
2084 		struct elf_phdr phdr;
2085 
2086 		phdr.p_type = PT_LOAD;
2087 		phdr.p_offset = offset;
2088 		phdr.p_vaddr = meta->start;
2089 		phdr.p_paddr = 0;
2090 		phdr.p_filesz = meta->dump_size;
2091 		phdr.p_memsz = meta->end - meta->start;
2092 		offset += phdr.p_filesz;
2093 		phdr.p_flags = 0;
2094 		if (meta->flags & VM_READ)
2095 			phdr.p_flags |= PF_R;
2096 		if (meta->flags & VM_WRITE)
2097 			phdr.p_flags |= PF_W;
2098 		if (meta->flags & VM_EXEC)
2099 			phdr.p_flags |= PF_X;
2100 		phdr.p_align = ELF_EXEC_PAGESIZE;
2101 
2102 		if (!dump_emit(cprm, &phdr, sizeof(phdr)))
2103 			goto end_coredump;
2104 	}
2105 
2106 	if (!elf_core_write_extra_phdrs(cprm, offset))
2107 		goto end_coredump;
2108 
2109 	/* write out the notes section */
2110 	if (!write_note_info(&info, cprm))
2111 		goto end_coredump;
2112 
2113 	/* For cell spufs */
2114 	if (elf_coredump_extra_notes_write(cprm))
2115 		goto end_coredump;
2116 
2117 	/* Align to page */
2118 	dump_skip_to(cprm, dataoff);
2119 
2120 	for (i = 0; i < cprm->vma_count; i++) {
2121 		struct core_vma_metadata *meta = cprm->vma_meta + i;
2122 
2123 		if (!dump_user_range(cprm, meta->start, meta->dump_size))
2124 			goto end_coredump;
2125 	}
2126 
2127 	if (!elf_core_write_extra_data(cprm))
2128 		goto end_coredump;
2129 
2130 	if (e_phnum == PN_XNUM) {
2131 		if (!dump_emit(cprm, shdr4extnum, sizeof(*shdr4extnum)))
2132 			goto end_coredump;
2133 	}
2134 
2135 end_coredump:
2136 	free_note_info(&info);
2137 	kfree(shdr4extnum);
2138 	kfree(phdr4note);
2139 	return has_dumped;
2140 }
2141 
2142 #endif		/* CONFIG_ELF_CORE */
2143 
2144 static int __init init_elf_binfmt(void)
2145 {
2146 	register_binfmt(&elf_format);
2147 	return 0;
2148 }
2149 
2150 static void __exit exit_elf_binfmt(void)
2151 {
2152 	/* Remove the COFF and ELF loaders. */
2153 	unregister_binfmt(&elf_format);
2154 }
2155 
2156 core_initcall(init_elf_binfmt);
2157 module_exit(exit_elf_binfmt);
2158 
2159 #ifdef CONFIG_BINFMT_ELF_KUNIT_TEST
2160 #include "binfmt_elf_test.c"
2161 #endif
2162