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