xref: /linux/fs/exec.c (revision aaf3d47e530616ed0cf9110ba8c537ace455dd90)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/fs/exec.c
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  */
7 
8 /*
9  * #!-checking implemented by tytso.
10  */
11 /*
12  * Demand-loading implemented 01.12.91 - no need to read anything but
13  * the header into memory. The inode of the executable is put into
14  * "current->executable", and page faults do the actual loading. Clean.
15  *
16  * Once more I can proudly say that linux stood up to being changed: it
17  * was less than 2 hours work to get demand-loading completely implemented.
18  *
19  * Demand loading changed July 1993 by Eric Youngdale.   Use mmap instead,
20  * current->executable is only used by the procfs.  This allows a dispatch
21  * table to check for several different types  of binary formats.  We keep
22  * trying until we recognize the file or we run out of supported binary
23  * formats.
24  */
25 
26 #include <linux/kernel_read_file.h>
27 #include <linux/slab.h>
28 #include <linux/file.h>
29 #include <linux/fdtable.h>
30 #include <linux/mm.h>
31 #include <linux/stat.h>
32 #include <linux/fcntl.h>
33 #include <linux/futex.h>
34 #include <linux/swap.h>
35 #include <linux/string.h>
36 #include <linux/init.h>
37 #include <linux/sched/mm.h>
38 #include <linux/sched/coredump.h>
39 #include <linux/sched/exec_state.h>
40 #include <linux/sched/signal.h>
41 #include <linux/sched/numa_balancing.h>
42 #include <linux/sched/task.h>
43 #include <linux/pagemap.h>
44 #include <linux/perf_event.h>
45 #include <linux/highmem.h>
46 #include <linux/spinlock.h>
47 #include <linux/key.h>
48 #include <linux/personality.h>
49 #include <linux/binfmts.h>
50 #include <linux/utsname.h>
51 #include <linux/pid_namespace.h>
52 #include <linux/module.h>
53 #include <linux/namei.h>
54 #include <linux/mount.h>
55 #include <linux/security.h>
56 #include <linux/syscalls.h>
57 #include <linux/tsacct_kern.h>
58 #include <linux/cn_proc.h>
59 #include <linux/audit.h>
60 #include <linux/kmod.h>
61 #include <linux/fsnotify.h>
62 #include <linux/fs_struct.h>
63 #include <linux/oom.h>
64 #include <linux/compat.h>
65 #include <linux/vmalloc.h>
66 #include <linux/io_uring.h>
67 #include <linux/syscall_user_dispatch.h>
68 #include <linux/coredump.h>
69 #include <linux/time_namespace.h>
70 #include <linux/user_events.h>
71 #include <linux/rseq.h>
72 #include <linux/ksm.h>
73 
74 #include <linux/uaccess.h>
75 #include <asm/mmu_context.h>
76 #include <asm/tlb.h>
77 
78 #include <trace/events/task.h>
79 #include "internal.h"
80 
81 #include <trace/events/sched.h>
82 
83 /* For vma exec functions. */
84 #include "../mm/internal.h"
85 
86 static int bprm_creds_from_file(struct linux_binprm *bprm);
87 
88 int suid_dumpable = 0;
89 
90 static LIST_HEAD(formats);
91 static DEFINE_RWLOCK(binfmt_lock);
92 
93 void __register_binfmt(struct linux_binfmt * fmt, int insert)
94 {
95 	write_lock(&binfmt_lock);
96 	insert ? list_add(&fmt->lh, &formats) :
97 		 list_add_tail(&fmt->lh, &formats);
98 	write_unlock(&binfmt_lock);
99 }
100 
101 EXPORT_SYMBOL(__register_binfmt);
102 
103 void unregister_binfmt(struct linux_binfmt * fmt)
104 {
105 	write_lock(&binfmt_lock);
106 	list_del(&fmt->lh);
107 	write_unlock(&binfmt_lock);
108 }
109 
110 EXPORT_SYMBOL(unregister_binfmt);
111 
112 static inline void put_binfmt(struct linux_binfmt * fmt)
113 {
114 	module_put(fmt->module);
115 }
116 
117 bool path_noexec(const struct path *path)
118 {
119 	/* If it's an anonymous inode make sure that we catch any shenanigans. */
120 	VFS_WARN_ON_ONCE(IS_ANON_FILE(d_inode(path->dentry)) &&
121 			 !(path->mnt->mnt_sb->s_iflags & SB_I_NOEXEC));
122 	return (path->mnt->mnt_flags & MNT_NOEXEC) ||
123 	       (path->mnt->mnt_sb->s_iflags & SB_I_NOEXEC);
124 }
125 
126 #ifdef CONFIG_MMU
127 /*
128  * The nascent bprm->mm is not visible until exec_mmap() but it can
129  * use a lot of memory, account these pages in current->mm temporary
130  * for oom_badness()->get_mm_rss(). Once exec succeeds or fails, we
131  * change the counter back via acct_arg_size(0).
132  */
133 static void acct_arg_size(struct linux_binprm *bprm, unsigned long pages)
134 {
135 	struct mm_struct *mm = current->mm;
136 	long diff = (long)(pages - bprm->vma_pages);
137 
138 	if (!mm || !diff)
139 		return;
140 
141 	bprm->vma_pages = pages;
142 	add_mm_counter(mm, MM_ANONPAGES, diff);
143 }
144 
145 static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
146 		int write)
147 {
148 	struct page *page;
149 	struct vm_area_struct *vma = bprm->vma;
150 	struct mm_struct *mm = bprm->mm;
151 	int ret;
152 
153 	/*
154 	 * Avoid relying on expanding the stack down in GUP (which
155 	 * does not work for STACK_GROWSUP anyway), and just do it
156 	 * ahead of time.
157 	 */
158 	if (!mmap_read_lock_maybe_expand(mm, vma, pos, write))
159 		return NULL;
160 
161 	/*
162 	 * We are doing an exec().  'current' is the process
163 	 * doing the exec and 'mm' is the new process's mm.
164 	 */
165 	ret = get_user_pages_remote(mm, pos, 1,
166 			write ? FOLL_WRITE : 0,
167 			&page, NULL);
168 	mmap_read_unlock(mm);
169 	if (ret <= 0)
170 		return NULL;
171 
172 	if (write)
173 		acct_arg_size(bprm, vma_pages(vma));
174 
175 	return page;
176 }
177 
178 static void put_arg_page(struct page *page)
179 {
180 	put_page(page);
181 }
182 
183 static void free_arg_pages(struct linux_binprm *bprm)
184 {
185 }
186 
187 static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
188 		struct page *page)
189 {
190 	flush_cache_page(bprm->vma, pos, page_to_pfn(page));
191 }
192 
193 static bool valid_arg_len(struct linux_binprm *bprm, long len)
194 {
195 	return len <= MAX_ARG_STRLEN;
196 }
197 
198 #else
199 
200 static inline void acct_arg_size(struct linux_binprm *bprm, unsigned long pages)
201 {
202 }
203 
204 static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
205 		int write)
206 {
207 	struct page *page;
208 
209 	page = bprm->page[pos / PAGE_SIZE];
210 	if (!page && write) {
211 		page = alloc_page(GFP_HIGHUSER|__GFP_ZERO);
212 		if (!page)
213 			return NULL;
214 		bprm->page[pos / PAGE_SIZE] = page;
215 	}
216 
217 	return page;
218 }
219 
220 static void put_arg_page(struct page *page)
221 {
222 }
223 
224 static void free_arg_page(struct linux_binprm *bprm, int i)
225 {
226 	if (bprm->page[i]) {
227 		__free_page(bprm->page[i]);
228 		bprm->page[i] = NULL;
229 	}
230 }
231 
232 static void free_arg_pages(struct linux_binprm *bprm)
233 {
234 	int i;
235 
236 	for (i = 0; i < MAX_ARG_PAGES; i++)
237 		free_arg_page(bprm, i);
238 }
239 
240 static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
241 		struct page *page)
242 {
243 }
244 
245 static bool valid_arg_len(struct linux_binprm *bprm, long len)
246 {
247 	return len <= bprm->p;
248 }
249 
250 #endif /* CONFIG_MMU */
251 
252 /*
253  * Create a new mm_struct and populate it with a temporary stack
254  * vm_area_struct.  We don't have enough context at this point to set the stack
255  * flags, permissions, and offset, so we use temporary values.  We'll update
256  * them later in setup_arg_pages().
257  */
258 static int bprm_mm_init(struct linux_binprm *bprm)
259 {
260 	int err;
261 	struct mm_struct *mm = NULL;
262 
263 	bprm->mm = mm = mm_alloc();
264 	err = -ENOMEM;
265 	if (!mm)
266 		goto err;
267 
268 	/* Staged for would_dump() narrowing; consumed by begin_new_exec(). */
269 	bprm->user_ns = get_user_ns(current_user_ns());
270 
271 	/* Save current stack limit for all calculations made during exec. */
272 	task_lock(current->group_leader);
273 	bprm->rlim_stack = current->signal->rlim[RLIMIT_STACK];
274 	task_unlock(current->group_leader);
275 
276 #ifndef CONFIG_MMU
277 	bprm->p = PAGE_SIZE * MAX_ARG_PAGES - sizeof(void *);
278 #else
279 	err = create_init_stack_vma(bprm->mm, &bprm->vma, &bprm->p);
280 	if (err)
281 		goto err;
282 #endif
283 
284 	return 0;
285 
286 err:
287 	if (mm) {
288 		bprm->mm = NULL;
289 		mmdrop(mm);
290 	}
291 
292 	return err;
293 }
294 
295 struct user_arg_ptr {
296 #ifdef CONFIG_COMPAT
297 	bool is_compat;
298 #endif
299 	union {
300 		const char __user *const __user *native;
301 #ifdef CONFIG_COMPAT
302 		const compat_uptr_t __user *compat;
303 #endif
304 	} ptr;
305 };
306 
307 static const char __user *get_user_arg_ptr(struct user_arg_ptr argv, int nr)
308 {
309 	const char __user *native;
310 
311 #ifdef CONFIG_COMPAT
312 	if (unlikely(argv.is_compat)) {
313 		compat_uptr_t compat;
314 
315 		if (get_user(compat, argv.ptr.compat + nr))
316 			return ERR_PTR(-EFAULT);
317 
318 		return compat_ptr(compat);
319 	}
320 #endif
321 
322 	if (get_user(native, argv.ptr.native + nr))
323 		return ERR_PTR(-EFAULT);
324 
325 	return native;
326 }
327 
328 /*
329  * count() counts the number of strings in array ARGV.
330  */
331 static int count(struct user_arg_ptr argv, int max)
332 {
333 	int i = 0;
334 
335 	if (argv.ptr.native != NULL) {
336 		for (;;) {
337 			const char __user *p = get_user_arg_ptr(argv, i);
338 
339 			if (!p)
340 				break;
341 
342 			if (IS_ERR(p))
343 				return -EFAULT;
344 
345 			if (i >= max)
346 				return -E2BIG;
347 			++i;
348 
349 			if (fatal_signal_pending(current))
350 				return -ERESTARTNOHAND;
351 			cond_resched();
352 		}
353 	}
354 	return i;
355 }
356 
357 static int count_strings_kernel(const char *const *argv)
358 {
359 	int i;
360 
361 	if (!argv)
362 		return 0;
363 
364 	for (i = 0; argv[i]; ++i) {
365 		if (i >= MAX_ARG_STRINGS)
366 			return -E2BIG;
367 		if (fatal_signal_pending(current))
368 			return -ERESTARTNOHAND;
369 		cond_resched();
370 	}
371 	return i;
372 }
373 
374 static inline int bprm_set_stack_limit(struct linux_binprm *bprm,
375 				       unsigned long limit)
376 {
377 #ifdef CONFIG_MMU
378 	/* Avoid a pathological bprm->p. */
379 	if (bprm->p < limit)
380 		return -E2BIG;
381 	bprm->argmin = bprm->p - limit;
382 #endif
383 	return 0;
384 }
385 static inline bool bprm_hit_stack_limit(struct linux_binprm *bprm)
386 {
387 #ifdef CONFIG_MMU
388 	return bprm->p < bprm->argmin;
389 #else
390 	return false;
391 #endif
392 }
393 
394 /*
395  * Calculate bprm->argmin from:
396  * - _STK_LIM
397  * - ARG_MAX
398  * - bprm->rlim_stack.rlim_cur
399  * - bprm->argc
400  * - bprm->envc
401  * - bprm->p
402  */
403 static int bprm_stack_limits(struct linux_binprm *bprm)
404 {
405 	unsigned long limit, ptr_size;
406 
407 	/*
408 	 * Limit to 1/4 of the max stack size or 3/4 of _STK_LIM
409 	 * (whichever is smaller) for the argv+env strings.
410 	 * This ensures that:
411 	 *  - the remaining binfmt code will not run out of stack space,
412 	 *  - the program will have a reasonable amount of stack left
413 	 *    to work from.
414 	 */
415 	limit = _STK_LIM / 4 * 3;
416 	limit = min(limit, bprm->rlim_stack.rlim_cur / 4);
417 	/*
418 	 * We've historically supported up to 32 pages (ARG_MAX)
419 	 * of argument strings even with small stacks
420 	 */
421 	limit = max_t(unsigned long, limit, ARG_MAX);
422 	/* Reject totally pathological counts. */
423 	if (bprm->argc < 0 || bprm->envc < 0)
424 		return -E2BIG;
425 	/*
426 	 * We must account for the size of all the argv and envp pointers to
427 	 * the argv and envp strings, since they will also take up space in
428 	 * the stack. They aren't stored until much later when we can't
429 	 * signal to the parent that the child has run out of stack space.
430 	 * Instead, calculate it here so it's possible to fail gracefully.
431 	 *
432 	 * In the case of argc = 0, make sure there is space for adding a
433 	 * empty string (which will bump argc to 1), to ensure confused
434 	 * userspace programs don't start processing from argv[1], thinking
435 	 * argc can never be 0, to keep them from walking envp by accident.
436 	 * See do_execveat_common().
437 	 */
438 	if (check_add_overflow(max(bprm->argc, 1), bprm->envc, &ptr_size) ||
439 	    check_mul_overflow(ptr_size, sizeof(void *), &ptr_size))
440 		return -E2BIG;
441 	if (limit <= ptr_size)
442 		return -E2BIG;
443 	limit -= ptr_size;
444 
445 	return bprm_set_stack_limit(bprm, limit);
446 }
447 
448 /*
449  * 'copy_strings()' copies argument/environment strings from the old
450  * processes's memory to the new process's stack.  The call to get_user_pages()
451  * ensures the destination page is created and not swapped out.
452  */
453 static int copy_strings(int argc, struct user_arg_ptr argv,
454 			struct linux_binprm *bprm)
455 {
456 	struct page *kmapped_page = NULL;
457 	char *kaddr = NULL;
458 	unsigned long kpos = 0;
459 	int ret;
460 
461 	while (argc-- > 0) {
462 		const char __user *str;
463 		int len;
464 		unsigned long pos;
465 
466 		ret = -EFAULT;
467 		str = get_user_arg_ptr(argv, argc);
468 		if (IS_ERR(str))
469 			goto out;
470 
471 		len = strnlen_user(str, MAX_ARG_STRLEN);
472 		if (!len)
473 			goto out;
474 
475 		ret = -E2BIG;
476 		if (!valid_arg_len(bprm, len))
477 			goto out;
478 
479 		/* We're going to work our way backwards. */
480 		pos = bprm->p;
481 		str += len;
482 		bprm->p -= len;
483 		if (bprm_hit_stack_limit(bprm))
484 			goto out;
485 
486 		while (len > 0) {
487 			int offset, bytes_to_copy;
488 
489 			if (fatal_signal_pending(current)) {
490 				ret = -ERESTARTNOHAND;
491 				goto out;
492 			}
493 			cond_resched();
494 
495 			offset = pos % PAGE_SIZE;
496 			if (offset == 0)
497 				offset = PAGE_SIZE;
498 
499 			bytes_to_copy = offset;
500 			if (bytes_to_copy > len)
501 				bytes_to_copy = len;
502 
503 			offset -= bytes_to_copy;
504 			pos -= bytes_to_copy;
505 			str -= bytes_to_copy;
506 			len -= bytes_to_copy;
507 
508 			if (!kmapped_page || kpos != (pos & PAGE_MASK)) {
509 				struct page *page;
510 
511 				page = get_arg_page(bprm, pos, 1);
512 				if (!page) {
513 					ret = -E2BIG;
514 					goto out;
515 				}
516 
517 				if (kmapped_page) {
518 					flush_dcache_page(kmapped_page);
519 					kunmap_local(kaddr);
520 					put_arg_page(kmapped_page);
521 				}
522 				kmapped_page = page;
523 				kaddr = kmap_local_page(kmapped_page);
524 				kpos = pos & PAGE_MASK;
525 				flush_arg_page(bprm, kpos, kmapped_page);
526 			}
527 			if (copy_from_user(kaddr+offset, str, bytes_to_copy)) {
528 				ret = -EFAULT;
529 				goto out;
530 			}
531 		}
532 	}
533 	ret = 0;
534 out:
535 	if (kmapped_page) {
536 		flush_dcache_page(kmapped_page);
537 		kunmap_local(kaddr);
538 		put_arg_page(kmapped_page);
539 	}
540 	return ret;
541 }
542 
543 /*
544  * Copy and argument/environment string from the kernel to the processes stack.
545  */
546 int copy_string_kernel(const char *arg, struct linux_binprm *bprm)
547 {
548 	int len = strnlen(arg, MAX_ARG_STRLEN) + 1 /* terminating NUL */;
549 	unsigned long pos = bprm->p;
550 
551 	if (len == 0)
552 		return -EFAULT;
553 	if (!valid_arg_len(bprm, len))
554 		return -E2BIG;
555 
556 	/* We're going to work our way backwards. */
557 	arg += len;
558 	bprm->p -= len;
559 	if (bprm_hit_stack_limit(bprm))
560 		return -E2BIG;
561 
562 	while (len > 0) {
563 		unsigned int bytes_to_copy = min(len,
564 				min_not_zero(offset_in_page(pos), PAGE_SIZE));
565 		struct page *page;
566 
567 		pos -= bytes_to_copy;
568 		arg -= bytes_to_copy;
569 		len -= bytes_to_copy;
570 
571 		page = get_arg_page(bprm, pos, 1);
572 		if (!page)
573 			return -E2BIG;
574 		flush_arg_page(bprm, pos & PAGE_MASK, page);
575 		memcpy_to_page(page, offset_in_page(pos), arg, bytes_to_copy);
576 		put_arg_page(page);
577 	}
578 
579 	return 0;
580 }
581 EXPORT_SYMBOL(copy_string_kernel);
582 
583 static int copy_strings_kernel(int argc, const char *const *argv,
584 			       struct linux_binprm *bprm)
585 {
586 	while (argc-- > 0) {
587 		int ret = copy_string_kernel(argv[argc], bprm);
588 		if (ret < 0)
589 			return ret;
590 		if (fatal_signal_pending(current))
591 			return -ERESTARTNOHAND;
592 		cond_resched();
593 	}
594 	return 0;
595 }
596 
597 #ifdef CONFIG_MMU
598 
599 /*
600  * Finalizes the stack vm_area_struct. The flags and permissions are updated,
601  * the stack is optionally relocated, and some extra space is added.
602  */
603 int setup_arg_pages(struct linux_binprm *bprm,
604 		    unsigned long stack_top,
605 		    int executable_stack)
606 {
607 	int ret;
608 	unsigned long stack_shift;
609 	struct mm_struct *mm = current->mm;
610 	struct vm_area_struct *vma = bprm->vma;
611 	struct vm_area_struct *prev = NULL;
612 	vm_flags_t vm_flags;
613 	unsigned long stack_base;
614 	unsigned long stack_size;
615 	unsigned long stack_expand;
616 	unsigned long rlim_stack;
617 	struct mmu_gather tlb;
618 	struct vma_iterator vmi;
619 
620 #ifdef CONFIG_STACK_GROWSUP
621 	/* Limit stack size */
622 	stack_base = bprm->rlim_stack.rlim_max;
623 
624 	stack_base = calc_max_stack_size(stack_base);
625 
626 	/* Add space for stack randomization. */
627 	if (current->flags & PF_RANDOMIZE)
628 		stack_base += (STACK_RND_MASK << PAGE_SHIFT);
629 
630 	/* Make sure we didn't let the argument array grow too large. */
631 	if (vma->vm_end - vma->vm_start > stack_base)
632 		return -ENOMEM;
633 
634 	stack_base = PAGE_ALIGN(stack_top - stack_base);
635 
636 	stack_shift = vma->vm_start - stack_base;
637 	mm->arg_start = bprm->p - stack_shift;
638 	bprm->p = vma->vm_end - stack_shift;
639 #else
640 	stack_top = arch_align_stack(stack_top);
641 	stack_top = PAGE_ALIGN(stack_top);
642 
643 	if (unlikely(stack_top < mmap_min_addr) ||
644 	    unlikely(vma->vm_end - vma->vm_start >= stack_top - mmap_min_addr))
645 		return -ENOMEM;
646 
647 	stack_shift = vma->vm_end - stack_top;
648 
649 	bprm->p -= stack_shift;
650 	mm->arg_start = bprm->p;
651 #endif
652 
653 	bprm->exec -= stack_shift;
654 
655 	if (mmap_write_lock_killable(mm))
656 		return -EINTR;
657 
658 	vm_flags = VM_STACK_FLAGS;
659 
660 	/*
661 	 * Adjust stack execute permissions; explicitly enable for
662 	 * EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X and leave alone
663 	 * (arch default) otherwise.
664 	 */
665 	if (unlikely(executable_stack == EXSTACK_ENABLE_X))
666 		vm_flags |= VM_EXEC;
667 	else if (executable_stack == EXSTACK_DISABLE_X)
668 		vm_flags &= ~VM_EXEC;
669 	vm_flags |= mm->def_flags;
670 	vm_flags |= VM_STACK_INCOMPLETE_SETUP;
671 
672 	vma_iter_init(&vmi, mm, vma->vm_start);
673 
674 	tlb_gather_mmu(&tlb, mm);
675 	ret = mprotect_fixup(&vmi, &tlb, vma, &prev, vma->vm_start, vma->vm_end,
676 			vm_flags);
677 	tlb_finish_mmu(&tlb);
678 
679 	if (ret)
680 		goto out_unlock;
681 	BUG_ON(prev != vma);
682 
683 	if (unlikely(vm_flags & VM_EXEC)) {
684 		pr_warn_once("process '%pD4' started with executable stack\n",
685 			     bprm->file);
686 	}
687 
688 	/* Move stack pages down in memory. */
689 	if (stack_shift) {
690 		/*
691 		 * During bprm_mm_init(), we create a temporary stack at STACK_TOP_MAX.  Once
692 		 * the binfmt code determines where the new stack should reside, we shift it to
693 		 * its final location.
694 		 */
695 		ret = relocate_vma_down(vma, stack_shift);
696 		if (ret)
697 			goto out_unlock;
698 	}
699 
700 	/* mprotect_fixup is overkill to remove the temporary stack flags */
701 	vm_flags_clear(vma, VM_STACK_INCOMPLETE_SETUP);
702 
703 	stack_expand = 131072UL; /* randomly 32*4k (or 2*64k) pages */
704 	stack_size = vma->vm_end - vma->vm_start;
705 	/*
706 	 * Align this down to a page boundary as expand_stack
707 	 * will align it up.
708 	 */
709 	rlim_stack = bprm->rlim_stack.rlim_cur & PAGE_MASK;
710 
711 	stack_expand = min(rlim_stack, stack_size + stack_expand);
712 
713 #ifdef CONFIG_STACK_GROWSUP
714 	stack_base = vma->vm_start + stack_expand;
715 #else
716 	stack_base = vma->vm_end - stack_expand;
717 #endif
718 	current->mm->start_stack = bprm->p;
719 	ret = expand_stack_locked(vma, stack_base);
720 	if (ret)
721 		ret = -EFAULT;
722 
723 out_unlock:
724 	mmap_write_unlock(mm);
725 	return ret;
726 }
727 EXPORT_SYMBOL(setup_arg_pages);
728 
729 #else
730 
731 /*
732  * Transfer the program arguments and environment from the holding pages
733  * onto the stack. The provided stack pointer is adjusted accordingly.
734  */
735 int transfer_args_to_stack(struct linux_binprm *bprm,
736 			   unsigned long *sp_location)
737 {
738 	unsigned long index, stop, sp;
739 	int ret = 0;
740 
741 	stop = bprm->p >> PAGE_SHIFT;
742 	sp = *sp_location;
743 
744 	for (index = MAX_ARG_PAGES; index-- > stop; ) {
745 		unsigned int offset = index == stop ? bprm->p & ~PAGE_MASK : 0;
746 		char *src = kmap_local_page(bprm->page[index]) + offset;
747 		sp -= PAGE_SIZE - offset;
748 		if (copy_to_user((void *) sp, src, PAGE_SIZE - offset) != 0)
749 			ret = -EFAULT;
750 		kunmap_local(src);
751 		if (ret)
752 			goto out;
753 	}
754 
755 	bprm->exec += *sp_location - MAX_ARG_PAGES * PAGE_SIZE;
756 	*sp_location = sp;
757 
758 out:
759 	return ret;
760 }
761 EXPORT_SYMBOL(transfer_args_to_stack);
762 
763 #endif /* CONFIG_MMU */
764 
765 /*
766  * On success, caller must call do_close_execat() on the returned
767  * struct file to close it.
768  */
769 static struct file *do_open_execat(int fd, struct filename *name, int flags)
770 {
771 	int err;
772 	struct file *file __free(fput) = NULL;
773 	struct open_flags open_exec_flags = {
774 		.open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC,
775 		.acc_mode = MAY_EXEC,
776 		.intent = LOOKUP_OPEN,
777 		.lookup_flags = LOOKUP_FOLLOW,
778 	};
779 
780 	if ((flags &
781 	     ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH | AT_EXECVE_CHECK)) != 0)
782 		return ERR_PTR(-EINVAL);
783 	if (flags & AT_SYMLINK_NOFOLLOW)
784 		open_exec_flags.lookup_flags &= ~LOOKUP_FOLLOW;
785 
786 	file = do_file_open(fd, name, &open_exec_flags);
787 	if (IS_ERR(file))
788 		return file;
789 
790 	if (path_noexec(&file->f_path))
791 		return ERR_PTR(-EACCES);
792 
793 	/*
794 	 * In the past the regular type check was here. It moved to may_open() in
795 	 * 633fb6ac3980 ("exec: move S_ISREG() check earlier"). Since then it is
796 	 * an invariant that all non-regular files error out before we get here.
797 	 */
798 	if (WARN_ON_ONCE(!S_ISREG(file_inode(file)->i_mode)))
799 		return ERR_PTR(-EACCES);
800 
801 	err = exe_file_deny_write_access(file);
802 	if (err)
803 		return ERR_PTR(err);
804 
805 	return no_free_ptr(file);
806 }
807 
808 /**
809  * open_exec - Open a path name for execution
810  *
811  * @name: path name to open with the intent of executing it.
812  *
813  * Returns ERR_PTR on failure or allocated struct file on success.
814  *
815  * As this is a wrapper for the internal do_open_execat(), callers
816  * must call exe_file_allow_write_access() before fput() on release. Also see
817  * do_close_execat().
818  */
819 struct file *open_exec(const char *name)
820 {
821 	CLASS(filename_kernel, filename)(name);
822 	return do_open_execat(AT_FDCWD, filename, 0);
823 }
824 EXPORT_SYMBOL(open_exec);
825 
826 #if defined(CONFIG_BINFMT_FLAT) || defined(CONFIG_BINFMT_ELF_FDPIC)
827 ssize_t read_code(struct file *file, unsigned long addr, loff_t pos, size_t len)
828 {
829 	ssize_t res = vfs_read(file, (void __user *)addr, len, &pos);
830 	if (res > 0)
831 		flush_icache_user_range(addr, addr + len);
832 	return res;
833 }
834 EXPORT_SYMBOL(read_code);
835 #endif
836 
837 /*
838  * Maps the mm_struct mm into the current task struct.
839  * On success, this function returns with exec_update_lock
840  * held for writing. The replaced address space is stashed in
841  * bprm->old_mm for setup_new_exec() to release outside the lock.
842  */
843 static int exec_mmap(struct linux_binprm *bprm)
844 {
845 	struct task_exec_state *exec_state __free(put_task_exec_state) = NULL;
846 	struct mm_struct *mm = bprm->mm;
847 	struct task_struct *tsk;
848 	struct mm_struct *old_mm, *active_mm;
849 	int ret;
850 
851 	exec_state = alloc_task_exec_state(bprm->user_ns);
852 	if (!exec_state)
853 		return -ENOMEM;
854 
855 	/* Notify parent that we're no longer interested in the old VM */
856 	tsk = current;
857 	old_mm = current->mm;
858 	/* Clean up futexes and release the mm */
859 	mm_exit_exec_release(tsk, old_mm);
860 
861 	ret = down_write_killable(&tsk->signal->exec_update_lock);
862 	if (ret)
863 		return ret;
864 
865 	if (old_mm) {
866 		/*
867 		 * If there is a pending fatal signal perhaps a signal
868 		 * whose default action is to create a coredump get
869 		 * out and die instead of going through with the exec.
870 		 */
871 		ret = mmap_read_lock_killable(old_mm);
872 		if (ret) {
873 			up_write(&tsk->signal->exec_update_lock);
874 			return ret;
875 		}
876 	}
877 
878 	task_lock(tsk);
879 	membarrier_exec_mmap(mm);
880 
881 	local_irq_disable();
882 	active_mm = tsk->active_mm;
883 	tsk->active_mm = mm;
884 	tsk->mm = mm;
885 	sched_cache_exec_mmap(tsk, mm);
886 	mm_init_cid(mm, tsk);
887 	exec_state = task_exec_state_replace(tsk, exec_state);
888 	/*
889 	 * This prevents preemption while active_mm is being loaded and
890 	 * it and mm are being updated, which could cause problems for
891 	 * lazy tlb mm refcounting when these are updated by context
892 	 * switches. Not all architectures can handle irqs off over
893 	 * activate_mm yet.
894 	 */
895 	if (!IS_ENABLED(CONFIG_ARCH_WANT_IRQS_OFF_ACTIVATE_MM))
896 		local_irq_enable();
897 	activate_mm(active_mm, mm);
898 	if (IS_ENABLED(CONFIG_ARCH_WANT_IRQS_OFF_ACTIVATE_MM))
899 		local_irq_enable();
900 	lru_gen_add_mm(mm);
901 	task_unlock(tsk);
902 	lru_gen_use_mm(mm);
903 	if (old_mm) {
904 		mmap_read_unlock(old_mm);
905 		BUG_ON(active_mm != old_mm);
906 		/* Defer teardown to setup_new_exec(), outside the exec locks. */
907 		bprm->old_mm = old_mm;
908 	} else {
909 		mmdrop_lazy_tlb(active_mm);
910 	}
911 	futex_exec_done(tsk);
912 	return 0;
913 }
914 
915 /* Release the address space replaced by exec, outside the exec locks. */
916 static void exec_mm_put_old(struct mm_struct *old_mm)
917 {
918 	setmax_mm_hiwater_rss(&current->signal->maxrss, old_mm);
919 	mm_update_next_owner(old_mm);
920 	mmput(old_mm);
921 }
922 
923 static int de_thread(struct task_struct *tsk)
924 {
925 	struct signal_struct *sig = tsk->signal;
926 	struct sighand_struct *oldsighand = tsk->sighand;
927 	spinlock_t *lock = &oldsighand->siglock;
928 
929 	if (thread_group_empty(tsk))
930 		goto no_thread_group;
931 
932 	/*
933 	 * Kill all other threads in the thread group.
934 	 */
935 	spin_lock_irq(lock);
936 	if ((sig->flags & SIGNAL_GROUP_EXIT) || sig->group_exec_task) {
937 		/*
938 		 * Another group action in progress, just
939 		 * return so that the signal is processed.
940 		 */
941 		spin_unlock_irq(lock);
942 		return -EAGAIN;
943 	}
944 
945 	sig->group_exec_task = tsk;
946 	sig->notify_count = zap_other_threads(tsk);
947 	if (!thread_group_leader(tsk))
948 		sig->notify_count--;
949 
950 	while (sig->notify_count) {
951 		__set_current_state(TASK_KILLABLE);
952 		spin_unlock_irq(lock);
953 		schedule();
954 		if (__fatal_signal_pending(tsk))
955 			goto killed;
956 		spin_lock_irq(lock);
957 	}
958 	spin_unlock_irq(lock);
959 
960 	/*
961 	 * At this point all other threads have exited, all we have to
962 	 * do is to wait for the thread group leader to become inactive,
963 	 * and to assume its PID:
964 	 */
965 	if (!thread_group_leader(tsk)) {
966 		struct task_struct *leader = tsk->group_leader;
967 
968 		for (;;) {
969 			cgroup_threadgroup_change_begin(tsk);
970 			write_lock_irq(&tasklist_lock);
971 			/*
972 			 * Do this under tasklist_lock to ensure that
973 			 * exit_notify() can't miss ->group_exec_task
974 			 */
975 			sig->notify_count = -1;
976 			if (likely(leader->exit_state))
977 				break;
978 			__set_current_state(TASK_KILLABLE);
979 			write_unlock_irq(&tasklist_lock);
980 			cgroup_threadgroup_change_end(tsk);
981 			schedule();
982 			if (__fatal_signal_pending(tsk))
983 				goto killed;
984 		}
985 
986 		/*
987 		 * The only record we have of the real-time age of a
988 		 * process, regardless of execs it's done, is start_time.
989 		 * All the past CPU time is accumulated in signal_struct
990 		 * from sister threads now dead.  But in this non-leader
991 		 * exec, nothing survives from the original leader thread,
992 		 * whose birth marks the true age of this process now.
993 		 * When we take on its identity by switching to its PID, we
994 		 * also take its birthdate (always earlier than our own).
995 		 */
996 		tsk->start_time = leader->start_time;
997 		tsk->start_boottime = leader->start_boottime;
998 
999 		BUG_ON(!same_thread_group(leader, tsk));
1000 		/*
1001 		 * An exec() starts a new thread group with the
1002 		 * TGID of the previous thread group. Rehash the
1003 		 * two threads with a switched PID, and release
1004 		 * the former thread group leader:
1005 		 */
1006 
1007 		/* Become a process group leader with the old leader's pid.
1008 		 * The old leader becomes a thread of the this thread group.
1009 		 */
1010 		exchange_tids(tsk, leader);
1011 		transfer_pid(leader, tsk, PIDTYPE_TGID);
1012 		transfer_pid(leader, tsk, PIDTYPE_PGID);
1013 		transfer_pid(leader, tsk, PIDTYPE_SID);
1014 
1015 		list_replace_rcu(&leader->tasks, &tsk->tasks);
1016 		list_replace_init(&leader->sibling, &tsk->sibling);
1017 
1018 		tsk->group_leader = tsk;
1019 		leader->group_leader = tsk;
1020 
1021 		tsk->exit_signal = SIGCHLD;
1022 		leader->exit_signal = -1;
1023 
1024 		BUG_ON(leader->exit_state != EXIT_ZOMBIE);
1025 		leader->exit_state = EXIT_DEAD;
1026 		/*
1027 		 * We are going to release_task()->ptrace_unlink() silently,
1028 		 * the tracer can sleep in do_wait(). EXIT_DEAD guarantees
1029 		 * the tracer won't block again waiting for this thread.
1030 		 */
1031 		if (unlikely(leader->ptrace))
1032 			__wake_up_parent(leader, leader->parent);
1033 		write_unlock_irq(&tasklist_lock);
1034 		cgroup_threadgroup_change_end(tsk);
1035 
1036 		release_task(leader);
1037 	}
1038 
1039 	sig->group_exec_task = NULL;
1040 	sig->notify_count = 0;
1041 
1042 no_thread_group:
1043 	/* we have changed execution domain */
1044 	tsk->exit_signal = SIGCHLD;
1045 
1046 	BUG_ON(!thread_group_leader(tsk));
1047 	return 0;
1048 
1049 killed:
1050 	/* protects against exit_notify() and __exit_signal() */
1051 	read_lock(&tasklist_lock);
1052 	sig->group_exec_task = NULL;
1053 	sig->notify_count = 0;
1054 	read_unlock(&tasklist_lock);
1055 	return -EAGAIN;
1056 }
1057 
1058 
1059 /*
1060  * This function makes sure the current process has its own signal table,
1061  * so that flush_signal_handlers can later reset the handlers without
1062  * disturbing other processes.  (Other processes might share the signal
1063  * table via the CLONE_SIGHAND option to clone().)
1064  */
1065 static int unshare_sighand(struct task_struct *me)
1066 {
1067 	struct sighand_struct *oldsighand = me->sighand;
1068 
1069 	if (refcount_read(&oldsighand->count) != 1) {
1070 		struct sighand_struct *newsighand;
1071 		/*
1072 		 * This ->sighand is shared with the CLONE_SIGHAND
1073 		 * but not CLONE_THREAD task, switch to the new one.
1074 		 */
1075 		newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1076 		if (!newsighand)
1077 			return -ENOMEM;
1078 
1079 		refcount_set(&newsighand->count, 1);
1080 
1081 		write_lock_irq(&tasklist_lock);
1082 		spin_lock(&oldsighand->siglock);
1083 		memcpy(newsighand->action, oldsighand->action,
1084 		       sizeof(newsighand->action));
1085 		rcu_assign_pointer(me->sighand, newsighand);
1086 		spin_unlock(&oldsighand->siglock);
1087 		write_unlock_irq(&tasklist_lock);
1088 
1089 		__cleanup_sighand(oldsighand);
1090 	}
1091 	return 0;
1092 }
1093 
1094 /*
1095  * This is unlocked -- the string will always be NUL-terminated, but
1096  * may show overlapping contents if racing concurrent reads.
1097  */
1098 void __set_task_comm(struct task_struct *tsk, const char *buf, bool exec)
1099 {
1100 	size_t len = strnlen(buf, sizeof(tsk->comm) - 1);
1101 
1102 	trace_task_rename(tsk, buf);
1103 	memcpy(tsk->comm, buf, len);
1104 	memset(&tsk->comm[len], 0, sizeof(tsk->comm) - len);
1105 	perf_event_comm(tsk, exec);
1106 }
1107 
1108 /*
1109  * The file the process presents as: its exe link and comm. A transparent
1110  * dispatch presents as the binary, which is bprm->executable.
1111  */
1112 static struct file *bprm_identity_file(const struct linux_binprm *bprm)
1113 {
1114 	if (bprm->interp_flags & BINPRM_FLAGS_TRANSPARENT_INTERP)
1115 		return bprm->executable;
1116 	return bprm->file;
1117 }
1118 
1119 /*
1120  * Calling this is the point of no return. None of the failures will be
1121  * seen by userspace since either the process is already taking a fatal
1122  * signal (via de_thread() or coredump), or will have SEGV raised
1123  * (after exec_mmap()) by search_binary_handler (see below).
1124  */
1125 int begin_new_exec(struct linux_binprm * bprm)
1126 {
1127 	struct task_struct *me = current;
1128 	struct files_struct *files = NULL;
1129 	int retval;
1130 
1131 	/* A pending PT_INTERP substitution this format cannot consume. */
1132 	if (bprm->loader)
1133 		return -ENOEXEC;
1134 
1135 	/* Once we are committed compute the creds */
1136 	retval = bprm_creds_from_file(bprm);
1137 	if (retval)
1138 		return retval;
1139 
1140 	/*
1141 	 * This tracepoint marks the point before flushing the old exec where
1142 	 * the current task is still unchanged, but errors are fatal (point of
1143 	 * no return). The later "sched_process_exec" tracepoint is called after
1144 	 * the current task has successfully switched to the new exec.
1145 	 */
1146 	trace_sched_prepare_exec(current, bprm);
1147 
1148 	/*
1149 	 * Ensure all future errors are fatal.
1150 	 */
1151 	bprm->point_of_no_return = true;
1152 
1153 	/*
1154 	 * Cancel any io_uring activity across execve. This runs task work
1155 	 * that may still create an io-wq worker, so do it while de_thread()
1156 	 * can still zap it.
1157 	 */
1158 	io_uring_task_cancel();
1159 
1160 	/* Make this the only thread in the thread group */
1161 	retval = de_thread(me);
1162 	if (retval)
1163 		goto out;
1164 
1165 	/*
1166 	 * This must be done here to ensure that POSIX CPU timers which were
1167 	 * armed on the current task are dequeued from me::posix_cputimers.
1168 	 * Otherwise in case of a TID switch the deletion of the related POSIX
1169 	 * timer would not remove an enqueued timer because the TID lookup
1170 	 * of the old TID fails.
1171 	 */
1172 	posixtimer_exec();
1173 
1174 	/* see the comment in check_unsafe_exec() */
1175 	current->fs->in_exec = 0;
1176 
1177 	/* Ensure the files table is not shared. */
1178 	retval = unshare_fd(CLONE_FILES, &files);
1179 	if (retval)
1180 		goto out;
1181 	if (files)
1182 		switch_files_struct(me, files);
1183 
1184 	/*
1185 	 * We have to apply CLOEXEC before we change whether the process is
1186 	 * dumpable (in setup_new_exec) to avoid a race with a process in userspace
1187 	 * trying to access the should-be-closed file descriptors of a process
1188 	 * undergoing exec(2).
1189 	 *
1190 	 * This can block on filesystem ->flush() and ->release() handlers,
1191 	 * including waiting for FUSE daemons, so do it before exec_mmap
1192 	 * takes the exec_update_lock.
1193 	 * This must happen after the point of no return, and after unsharing
1194 	 * the FD table.
1195 	 */
1196 	close_cloexec_files(me->files);
1197 
1198 	/*
1199 	 * Must be called _before_ exec_mmap() as bprm->mm is
1200 	 * not visible until then. Doing it here also ensures
1201 	 * we don't race against replace_mm_exe_file().
1202 	 */
1203 	retval = set_mm_exe_file(bprm->mm, bprm_identity_file(bprm));
1204 	if (retval)
1205 		goto out;
1206 
1207 	/* If the binary is not readable then enforce mm->dumpable=0 */
1208 	would_dump(bprm, bprm->file);
1209 	if (bprm->have_execfd)
1210 		would_dump(bprm, bprm->executable);
1211 
1212 	/*
1213 	 * Release all of the old mmap stuff
1214 	 */
1215 	acct_arg_size(bprm, 0);
1216 	retval = exec_mmap(bprm);
1217 	if (retval)
1218 		goto out;
1219 
1220 	bprm->mm = NULL;
1221 
1222 	retval = exec_task_namespaces();
1223 	if (retval)
1224 		goto out_unlock;
1225 
1226 	/*
1227 	 * Make the signal table private.
1228 	 */
1229 	retval = unshare_sighand(me);
1230 	if (retval)
1231 		goto out_unlock;
1232 
1233 	me->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC |
1234 					PF_NOFREEZE | PF_NO_SETAFFINITY);
1235 	flush_thread();
1236 	me->personality &= ~bprm->per_clear;
1237 
1238 	clear_syscall_work_syscall_user_dispatch(me);
1239 
1240 	if (bprm->secureexec) {
1241 		/* Make sure parent cannot signal privileged process. */
1242 		me->pdeath_signal = 0;
1243 
1244 		/*
1245 		 * For secureexec, reset the stack limit to sane default to
1246 		 * avoid bad behavior from the prior rlimits. This has to
1247 		 * happen before arch_pick_mmap_layout(), which examines
1248 		 * RLIMIT_STACK, but after the point of no return to avoid
1249 		 * needing to clean up the change on failure.
1250 		 */
1251 		if (bprm->rlim_stack.rlim_cur > _STK_LIM)
1252 			bprm->rlim_stack.rlim_cur = _STK_LIM;
1253 	}
1254 
1255 	me->sas_ss_sp = me->sas_ss_size = 0;
1256 
1257 	/*
1258 	 * Figure out dumpability. Note that this checking only of current
1259 	 * is wrong, but userspace depends on it. This should be testing
1260 	 * bprm->secureexec instead.
1261 	 */
1262 	if (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP ||
1263 	    !(uid_eq(current_euid(), current_uid()) &&
1264 	      gid_eq(current_egid(), current_gid())))
1265 		task_exec_state_set_dumpable(suid_dumpable);
1266 	else
1267 		task_exec_state_set_dumpable(TASK_DUMPABLE_OWNER);
1268 
1269 	perf_event_exec();
1270 
1271 	/*
1272 	 * If the original filename was empty, alloc_bprm() made up a path
1273 	 * that will probably not be useful to admins running ps or similar.
1274 	 * Let's fix it up to be something reasonable.
1275 	 */
1276 	if (bprm->comm_from_dentry) {
1277 		struct file *comm_file = bprm_identity_file(bprm);
1278 
1279 		/*
1280 		 * Hold RCU lock to keep the name from being freed behind our back.
1281 		 * Use acquire semantics to make sure the terminating NUL from
1282 		 * __d_alloc() is seen.
1283 		 *
1284 		 * Note, we're deliberately sloppy here. We don't need to care about
1285 		 * detecting a concurrent rename and just want a terminated name.
1286 		 */
1287 		rcu_read_lock();
1288 		__set_task_comm(me, smp_load_acquire(&comm_file->f_path.dentry->d_name.name),
1289 				true);
1290 		rcu_read_unlock();
1291 	} else {
1292 		__set_task_comm(me, kbasename(bprm->filename), true);
1293 	}
1294 
1295 	/* An exec changes our domain. We are no longer part of the thread
1296 	   group */
1297 	WRITE_ONCE(me->self_exec_id, me->self_exec_id + 1);
1298 	flush_signal_handlers(me, 0);
1299 
1300 	retval = set_cred_ucounts(bprm->cred);
1301 	if (retval < 0)
1302 		goto out_unlock;
1303 
1304 	/*
1305 	 * install the new credentials for this executable
1306 	 */
1307 	security_bprm_committing_creds(bprm);
1308 
1309 	commit_creds(bprm->cred);
1310 	bprm->cred = NULL;
1311 
1312 	/*
1313 	 * Disable monitoring for regular users
1314 	 * when executing setuid binaries. Must
1315 	 * wait until new credentials are committed
1316 	 * by commit_creds() above
1317 	 */
1318 	if (task_exec_state_get_dumpable(me) != TASK_DUMPABLE_OWNER)
1319 		perf_event_exit_task(me);
1320 	/*
1321 	 * cred_guard_mutex must be held at least to this point to prevent
1322 	 * ptrace_attach() from altering our determination of the task's
1323 	 * credentials; any time after this it may be unlocked.
1324 	 */
1325 	security_bprm_committed_creds(bprm);
1326 
1327 	/* Pass the opened binary to the interpreter. */
1328 	if (bprm->have_execfd) {
1329 		struct file *executable = bprm->executable;
1330 
1331 		/* mm->exe_file carries its own write denial now so drop it. */
1332 		exe_file_allow_write_access(executable);
1333 		bprm->executable = NULL;
1334 		retval = FD_ADD(0, executable);
1335 		if (retval < 0) {
1336 			/* The reference was not consumed. */
1337 			fput(executable);
1338 			goto out_unlock;
1339 		}
1340 		bprm->execfd = retval;
1341 	}
1342 	return 0;
1343 
1344 out_unlock:
1345 	up_write(&me->signal->exec_update_lock);
1346 	if (!bprm->cred)
1347 		mutex_unlock(&me->signal->cred_guard_mutex);
1348 
1349 out:
1350 	return retval;
1351 }
1352 EXPORT_SYMBOL(begin_new_exec);
1353 
1354 void would_dump(struct linux_binprm *bprm, struct file *file)
1355 {
1356 	struct inode *inode = file_inode(file);
1357 	const struct mnt_idmap *idmap = file_mnt_idmap(file);
1358 	if (inode_permission(idmap, inode, MAY_READ) < 0) {
1359 		struct user_namespace *old, *user_ns;
1360 		bprm->interp_flags |= BINPRM_FLAGS_ENFORCE_NONDUMP;
1361 
1362 		/* Ensure bprm->user_ns contains the executable. */
1363 		user_ns = old = bprm->user_ns;
1364 		while ((user_ns != &init_user_ns) &&
1365 		       !privileged_wrt_inode_uidgid(user_ns, idmap, inode))
1366 			user_ns = user_ns->parent;
1367 
1368 		if (old != user_ns) {
1369 			bprm->user_ns = get_user_ns(user_ns);
1370 			put_user_ns(old);
1371 		}
1372 	}
1373 }
1374 EXPORT_SYMBOL(would_dump);
1375 
1376 void setup_new_exec(struct linux_binprm * bprm)
1377 {
1378 	/* Setup things that can depend upon the personality */
1379 	struct task_struct *me = current;
1380 
1381 	arch_pick_mmap_layout(me->mm, &bprm->rlim_stack);
1382 
1383 	arch_setup_new_exec();
1384 
1385 	/* Set the new mm task size. We have to do that late because it may
1386 	 * depend on TIF_32BIT which is only updated in flush_thread() on
1387 	 * some architectures like powerpc
1388 	 */
1389 	me->mm->task_size = TASK_SIZE;
1390 	up_write(&me->signal->exec_update_lock);
1391 	mutex_unlock(&me->signal->cred_guard_mutex);
1392 
1393 	/* The exec locks are dropped: release the old address space now. */
1394 	if (bprm->old_mm) {
1395 		exec_mm_put_old(bprm->old_mm);
1396 		bprm->old_mm = NULL;
1397 	}
1398 }
1399 EXPORT_SYMBOL(setup_new_exec);
1400 
1401 /* Runs immediately before start_thread() takes over. */
1402 void finalize_exec(struct linux_binprm *bprm)
1403 {
1404 	/* Store any stack rlimit changes before starting thread. */
1405 	task_lock(current->group_leader);
1406 	current->signal->rlim[RLIMIT_STACK] = bprm->rlim_stack;
1407 	task_unlock(current->group_leader);
1408 }
1409 EXPORT_SYMBOL(finalize_exec);
1410 
1411 /*
1412  * Prepare credentials and lock ->cred_guard_mutex.
1413  * setup_new_exec() commits the new creds and drops the lock.
1414  * Or, if exec fails before, free_bprm() should release ->cred
1415  * and unlock.
1416  */
1417 static int prepare_bprm_creds(struct linux_binprm *bprm)
1418 {
1419 	if (mutex_lock_interruptible(&current->signal->cred_guard_mutex))
1420 		return -ERESTARTNOINTR;
1421 
1422 	bprm->cred = prepare_exec_creds();
1423 	if (likely(bprm->cred))
1424 		return 0;
1425 
1426 	mutex_unlock(&current->signal->cred_guard_mutex);
1427 	return -ENOMEM;
1428 }
1429 
1430 /* Matches do_open_execat() */
1431 static void do_close_execat(struct file *file)
1432 {
1433 	if (!file)
1434 		return;
1435 	exe_file_allow_write_access(file);
1436 	fput(file);
1437 }
1438 
1439 /**
1440  * bprm_open_interpreter - open the interpreter the binary asks for
1441  * @bprm: binary that is being executed
1442  * @path: the interpreter path named in the binary's PT_INTERP
1443  *
1444  * A binfmt_misc loader entry substitutes for the interpreter the binary
1445  * names. Hand out the stashed substitute if there is one and open @path
1446  * if there is not. The caller owns the reference either way and releases
1447  * it like any other open_exec() one.
1448  *
1449  * Return: the interpreter on success, an ERR_PTR on failure
1450  */
1451 struct file *bprm_open_interpreter(struct linux_binprm *bprm, const char *path)
1452 {
1453 	if (bprm->loader)
1454 		return no_free_ptr(bprm->loader);
1455 	return open_exec(path);
1456 }
1457 
1458 /**
1459  * bprm_drop_loader - discard a PT_INTERP substitute that does not apply
1460  * @bprm: binary that is being executed
1461  *
1462  * A binary without PT_INTERP has nothing to substitute for, so drop the
1463  * override and let the binary load natively rather than have
1464  * begin_new_exec() refuse it. A no-op once bprm_open_interpreter() took
1465  * the substitute.
1466  */
1467 void bprm_drop_loader(struct linux_binprm *bprm)
1468 {
1469 	do_close_execat(no_free_ptr(bprm->loader));
1470 }
1471 
1472 static void free_bprm(struct linux_binprm *bprm)
1473 {
1474 	if (bprm->mm) {
1475 		acct_arg_size(bprm, 0);
1476 		mmput(bprm->mm);
1477 	}
1478 	if (bprm->user_ns)
1479 		put_user_ns(bprm->user_ns);
1480 	free_arg_pages(bprm);
1481 	if (bprm->cred) {
1482 		/* in case exec fails before de_thread() succeeds */
1483 		current->fs->in_exec = 0;
1484 		mutex_unlock(&current->signal->cred_guard_mutex);
1485 		abort_creds(bprm->cred);
1486 	}
1487 	/* exec swapped the mm but failed before setup_new_exec() freed it */
1488 	if (bprm->old_mm)
1489 		exec_mm_put_old(bprm->old_mm);
1490 	/* An unconsumed PT_INTERP substitute from a binfmt_misc loader entry. */
1491 	bprm_drop_loader(bprm);
1492 	do_close_execat(bprm->file);
1493 	do_close_execat(bprm->executable);
1494 	/* If a binfmt changed the interp, free it. */
1495 	if (bprm->interp != bprm->filename)
1496 		kfree(bprm->interp);
1497 	kfree(bprm->bpf_interp);
1498 	if (bprm->bpf_interp_file)
1499 		fput(bprm->bpf_interp_file);
1500 	kfree(bprm->bpf_interp_arg);
1501 	kfree(bprm->fdpath);
1502 	kfree(bprm);
1503 }
1504 
1505 static struct linux_binprm *alloc_bprm(int fd, struct filename *filename, int flags)
1506 {
1507 	struct linux_binprm *bprm;
1508 	struct file *file;
1509 	int retval = -ENOMEM;
1510 
1511 	file = do_open_execat(fd, filename, flags);
1512 	if (IS_ERR(file))
1513 		return ERR_CAST(file);
1514 
1515 	bprm = kzalloc_obj(*bprm);
1516 	if (!bprm) {
1517 		do_close_execat(file);
1518 		return ERR_PTR(-ENOMEM);
1519 	}
1520 
1521 	bprm->file = file;
1522 
1523 	if (fd == AT_FDCWD || filename->name[0] == '/') {
1524 		bprm->filename = filename->name;
1525 	} else {
1526 		if (filename->name[0] == '\0') {
1527 			bprm->fdpath = kasprintf(GFP_KERNEL, "/dev/fd/%d", fd);
1528 			bprm->comm_from_dentry = 1;
1529 		} else {
1530 			bprm->fdpath = kasprintf(GFP_KERNEL, "/dev/fd/%d/%s",
1531 						  fd, filename->name);
1532 		}
1533 		if (!bprm->fdpath)
1534 			goto out_free;
1535 
1536 		/*
1537 		 * Record that a name derived from an O_CLOEXEC fd will be
1538 		 * inaccessible after exec.  This allows the code in exec to
1539 		 * choose to fail when the executable is not mmaped into the
1540 		 * interpreter and an open file descriptor is not passed to
1541 		 * the interpreter.  This makes for a better user experience
1542 		 * than having the interpreter start and then immediately fail
1543 		 * when it finds the executable is inaccessible.
1544 		 */
1545 		if (get_close_on_exec(fd))
1546 			bprm->interp_flags |= BINPRM_FLAGS_PATH_INACCESSIBLE;
1547 
1548 		bprm->filename = bprm->fdpath;
1549 	}
1550 	bprm->interp = bprm->filename;
1551 
1552 	/*
1553 	 * At this point, security_file_open() has already been called (with
1554 	 * __FMODE_EXEC) and access control checks for AT_EXECVE_CHECK will
1555 	 * stop just after the security_bprm_creds_for_exec() call in
1556 	 * bprm_execve().  Indeed, the kernel should not try to parse the
1557 	 * content of the file with exec_binprm() nor change the calling
1558 	 * thread, which means that the following security functions will not
1559 	 * be called:
1560 	 * - security_bprm_check()
1561 	 * - security_bprm_creds_from_file()
1562 	 * - security_bprm_committing_creds()
1563 	 * - security_bprm_committed_creds()
1564 	 */
1565 	bprm->is_check = !!(flags & AT_EXECVE_CHECK);
1566 
1567 	retval = bprm_mm_init(bprm);
1568 	if (!retval)
1569 		return bprm;
1570 
1571 out_free:
1572 	free_bprm(bprm);
1573 	return ERR_PTR(retval);
1574 }
1575 
1576 DEFINE_CLASS(bprm, struct linux_binprm *, if (!IS_ERR(_T)) free_bprm(_T),
1577 	alloc_bprm(fd, name, flags), int fd, struct filename *name, int flags)
1578 
1579 int bprm_change_interp(const char *interp, struct linux_binprm *bprm)
1580 {
1581 	/* If a binfmt changed the interp, free it first. */
1582 	if (bprm->interp != bprm->filename)
1583 		kfree(bprm->interp);
1584 	bprm->interp = kstrdup(interp, GFP_KERNEL);
1585 	if (!bprm->interp)
1586 		return -ENOMEM;
1587 	return 0;
1588 }
1589 EXPORT_SYMBOL(bprm_change_interp);
1590 
1591 /*
1592  * determine how safe it is to execute the proposed program
1593  * - the caller must hold ->cred_guard_mutex to protect against
1594  *   PTRACE_ATTACH or seccomp thread-sync
1595  */
1596 static void check_unsafe_exec(struct linux_binprm *bprm)
1597 {
1598 	struct task_struct *p = current, *t;
1599 	unsigned n_fs;
1600 
1601 	if (p->ptrace)
1602 		bprm->unsafe |= LSM_UNSAFE_PTRACE;
1603 
1604 	/*
1605 	 * This isn't strictly necessary, but it makes it harder for LSMs to
1606 	 * mess up.
1607 	 */
1608 	if (task_no_new_privs(current))
1609 		bprm->unsafe |= LSM_UNSAFE_NO_NEW_PRIVS;
1610 
1611 	/*
1612 	 * If another task is sharing our fs, we cannot safely
1613 	 * suid exec because the differently privileged task
1614 	 * will be able to manipulate the current directory, etc.
1615 	 * It would be nice to force an unshare instead...
1616 	 *
1617 	 * Otherwise we set fs->in_exec = 1 to deny clone(CLONE_FS)
1618 	 * from another sub-thread until de_thread() succeeds, this
1619 	 * state is protected by cred_guard_mutex we hold.
1620 	 */
1621 	n_fs = 1;
1622 	read_seqlock_excl(&p->fs->seq);
1623 	rcu_read_lock();
1624 	for_other_threads(p, t) {
1625 		if (t->fs == p->fs)
1626 			n_fs++;
1627 	}
1628 	rcu_read_unlock();
1629 
1630 	/* "users" and "in_exec" locked for copy_fs() */
1631 	if (p->fs->users > n_fs)
1632 		bprm->unsafe |= LSM_UNSAFE_SHARE;
1633 	else
1634 		p->fs->in_exec = 1;
1635 	read_sequnlock_excl(&p->fs->seq);
1636 }
1637 
1638 static void bprm_fill_uid(struct linux_binprm *bprm, struct file *file)
1639 {
1640 	/* Handle suid and sgid on files */
1641 	const struct mnt_idmap *idmap;
1642 	struct inode *inode = file_inode(file);
1643 	unsigned int mode;
1644 	vfsuid_t vfsuid;
1645 	vfsgid_t vfsgid;
1646 	int err;
1647 
1648 	if (!mnt_may_suid(file->f_path.mnt))
1649 		return;
1650 
1651 	if (task_no_new_privs(current))
1652 		return;
1653 
1654 	mode = READ_ONCE(inode->i_mode);
1655 	if (!(mode & (S_ISUID|S_ISGID)))
1656 		return;
1657 
1658 	idmap = file_mnt_idmap(file);
1659 
1660 	/* Be careful if suid/sgid is set */
1661 	inode_lock(inode);
1662 
1663 	/* Atomically reload and check mode/uid/gid now that lock held. */
1664 	mode = inode->i_mode;
1665 	vfsuid = i_uid_into_vfsuid(idmap, inode);
1666 	vfsgid = i_gid_into_vfsgid(idmap, inode);
1667 	err = inode_permission(idmap, inode, MAY_EXEC);
1668 	inode_unlock(inode);
1669 
1670 	/* Did the exec bit vanish out from under us? Give up. */
1671 	if (err)
1672 		return;
1673 
1674 	/* We ignore suid/sgid if there are no mappings for them in the ns */
1675 	if (!vfsuid_has_mapping(bprm->cred->user_ns, vfsuid) ||
1676 	    !vfsgid_has_mapping(bprm->cred->user_ns, vfsgid))
1677 		return;
1678 
1679 	if (mode & S_ISUID) {
1680 		bprm->per_clear |= PER_CLEAR_ON_SETID;
1681 		bprm->cred->euid = vfsuid_into_kuid(vfsuid);
1682 	}
1683 
1684 	if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
1685 		bprm->per_clear |= PER_CLEAR_ON_SETID;
1686 		bprm->cred->egid = vfsgid_into_kgid(vfsgid);
1687 	}
1688 }
1689 
1690 /*
1691  * Compute brpm->cred based upon the final binary.
1692  */
1693 static int bprm_creds_from_file(struct linux_binprm *bprm)
1694 {
1695 	/* Compute creds based on which file? */
1696 	struct file *file = bprm->execfd_creds ? bprm->executable : bprm->file;
1697 
1698 	bprm_fill_uid(bprm, file);
1699 	return security_bprm_creds_from_file(bprm, file);
1700 }
1701 
1702 /*
1703  * Fill the binprm structure from the inode.
1704  * Read the first BINPRM_BUF_SIZE bytes
1705  *
1706  * This may be called multiple times for binary chains (scripts for example).
1707  */
1708 static int prepare_binprm(struct linux_binprm *bprm)
1709 {
1710 	loff_t pos = 0;
1711 
1712 	memset(bprm->buf, 0, BINPRM_BUF_SIZE);
1713 	return kernel_read(bprm->file, bprm->buf, BINPRM_BUF_SIZE, &pos);
1714 }
1715 
1716 /*
1717  * Arguments are '\0' separated strings found at the location bprm->p
1718  * points to; chop off the first by relocating brpm->p to right after
1719  * the first '\0' encountered.
1720  */
1721 int remove_arg_zero(struct linux_binprm *bprm)
1722 {
1723 	unsigned long offset;
1724 	char *kaddr;
1725 	struct page *page;
1726 
1727 	if (!bprm->argc)
1728 		return 0;
1729 
1730 	do {
1731 		offset = bprm->p & ~PAGE_MASK;
1732 		page = get_arg_page(bprm, bprm->p, 0);
1733 		if (!page)
1734 			return -EFAULT;
1735 		kaddr = kmap_local_page(page);
1736 
1737 		for (; offset < PAGE_SIZE && kaddr[offset];
1738 				offset++, bprm->p++)
1739 			;
1740 
1741 		kunmap_local(kaddr);
1742 		put_arg_page(page);
1743 	} while (offset == PAGE_SIZE);
1744 
1745 	bprm->p++;
1746 	bprm->argc--;
1747 
1748 	return 0;
1749 }
1750 EXPORT_SYMBOL(remove_arg_zero);
1751 
1752 /*
1753  * cycle the list of binary formats handler, until one recognizes the image
1754  */
1755 static int search_binary_handler(struct linux_binprm *bprm)
1756 {
1757 	struct linux_binfmt *fmt;
1758 	int retval;
1759 
1760 	retval = prepare_binprm(bprm);
1761 	if (retval < 0)
1762 		return retval;
1763 
1764 	retval = security_bprm_check(bprm);
1765 	if (retval)
1766 		return retval;
1767 
1768 	read_lock(&binfmt_lock);
1769 	list_for_each_entry(fmt, &formats, lh) {
1770 		if (!try_module_get(fmt->module))
1771 			continue;
1772 		read_unlock(&binfmt_lock);
1773 
1774 		retval = fmt->load_binary(bprm);
1775 
1776 		read_lock(&binfmt_lock);
1777 		put_binfmt(fmt);
1778 		if (bprm->point_of_no_return || (retval != -ENOEXEC)) {
1779 			read_unlock(&binfmt_lock);
1780 			return retval;
1781 		}
1782 	}
1783 	read_unlock(&binfmt_lock);
1784 
1785 	return -ENOEXEC;
1786 }
1787 
1788 /* binfmt handlers will call back into begin_new_exec() on success. */
1789 static int exec_binprm(struct linux_binprm *bprm)
1790 {
1791 	pid_t old_pid, old_vpid;
1792 	int ret, depth;
1793 
1794 	/* Need to fetch pid before load_binary changes it */
1795 	old_pid = current->pid;
1796 	rcu_read_lock();
1797 	old_vpid = task_pid_nr_ns(current, task_active_pid_ns(current->parent));
1798 	rcu_read_unlock();
1799 
1800 	/* This allows 5 levels of binfmt rewrites before failing hard. */
1801 	for (depth = 0;; depth++) {
1802 		struct file *exec;
1803 		if (depth > 5)
1804 			return -ELOOP;
1805 
1806 		ret = search_binary_handler(bprm);
1807 		if (ret < 0)
1808 			return ret;
1809 		if (!bprm->interpreter)
1810 			break;
1811 
1812 		/* A stashed PT_INTERP substitute belonged to the replaced file. */
1813 		bprm_drop_loader(bprm);
1814 
1815 		exec = bprm->file;
1816 		bprm->file = bprm->interpreter;
1817 		bprm->interpreter = NULL;
1818 
1819 		if (unlikely(bprm->have_execfd)) {
1820 			if (bprm->executable) {
1821 				do_close_execat(exec);
1822 				return -ENOEXEC;
1823 			}
1824 			/* Kept for AT_EXECFD; the write denial rides along until hand-over. */
1825 			bprm->executable = exec;
1826 		} else {
1827 			do_close_execat(exec);
1828 		}
1829 	}
1830 
1831 	audit_bprm(bprm);
1832 	trace_sched_process_exec(current, old_pid, bprm);
1833 	ptrace_event(PTRACE_EVENT_EXEC, old_vpid);
1834 	proc_exec_connector(current);
1835 	return 0;
1836 }
1837 
1838 static int bprm_execve(struct linux_binprm *bprm)
1839 {
1840 	int retval;
1841 
1842 	retval = prepare_bprm_creds(bprm);
1843 	if (retval)
1844 		return retval;
1845 
1846 	/*
1847 	 * Check for unsafe execution states before exec_binprm(), which
1848 	 * will call back into begin_new_exec(), into bprm_creds_from_file(),
1849 	 * where setuid-ness is evaluated.
1850 	 */
1851 	check_unsafe_exec(bprm);
1852 	current->in_execve = 1;
1853 	sched_mm_cid_before_execve(current);
1854 
1855 	sched_exec();
1856 
1857 	/* Set the unchanging part of bprm->cred */
1858 	retval = security_bprm_creds_for_exec(bprm);
1859 	if (retval || bprm->is_check)
1860 		goto out;
1861 
1862 	retval = exec_binprm(bprm);
1863 	if (retval < 0)
1864 		goto out;
1865 
1866 	sched_mm_cid_after_execve(current);
1867 	rseq_execve(current);
1868 	/* execve succeeded */
1869 	current->in_execve = 0;
1870 	user_events_execve(current);
1871 	acct_update_integrals(current);
1872 	task_numa_free(current, false);
1873 	return retval;
1874 
1875 out:
1876 	/*
1877 	 * If past the point of no return ensure the code never
1878 	 * returns to the userspace process.  Use an existing fatal
1879 	 * signal if present otherwise terminate the process with
1880 	 * SIGSEGV.
1881 	 */
1882 	if (bprm->point_of_no_return && !fatal_signal_pending(current))
1883 		force_fatal_sig(SIGSEGV);
1884 
1885 	sched_mm_cid_after_execve(current);
1886 	rseq_force_update();
1887 	current->in_execve = 0;
1888 
1889 	return retval;
1890 }
1891 
1892 static int do_execveat_common(int fd, struct filename *filename,
1893 			      struct user_arg_ptr argv,
1894 			      struct user_arg_ptr envp,
1895 			      int flags)
1896 {
1897 	int retval;
1898 
1899 	/*
1900 	 * We move the actual failure in case of RLIMIT_NPROC excess from
1901 	 * set*uid() to execve() because too many poorly written programs
1902 	 * don't check setuid() return code.  Here we additionally recheck
1903 	 * whether NPROC limit is still exceeded.
1904 	 */
1905 	if ((current->flags & PF_NPROC_EXCEEDED) &&
1906 	    is_rlimit_overlimit(current_ucounts(), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC)))
1907 		return -EAGAIN;
1908 
1909 	/* We're below the limit (still or again), so we don't want to make
1910 	 * further execve() calls fail. */
1911 	current->flags &= ~PF_NPROC_EXCEEDED;
1912 
1913 	CLASS(bprm, bprm)(fd, filename, flags);
1914 	if (IS_ERR(bprm))
1915 		return PTR_ERR(bprm);
1916 
1917 	retval = count(argv, MAX_ARG_STRINGS);
1918 	if (retval < 0)
1919 		return retval;
1920 	bprm->argc = retval;
1921 
1922 	retval = count(envp, MAX_ARG_STRINGS);
1923 	if (retval < 0)
1924 		return retval;
1925 	bprm->envc = retval;
1926 
1927 	retval = bprm_stack_limits(bprm);
1928 	if (retval < 0)
1929 		return retval;
1930 
1931 	retval = copy_string_kernel(bprm->filename, bprm);
1932 	if (retval < 0)
1933 		return retval;
1934 	bprm->exec = bprm->p;
1935 
1936 	retval = copy_strings(bprm->envc, envp, bprm);
1937 	if (retval < 0)
1938 		return retval;
1939 
1940 	retval = copy_strings(bprm->argc, argv, bprm);
1941 	if (retval < 0)
1942 		return retval;
1943 
1944 	/*
1945 	 * When argv is empty, add an empty string ("") as argv[0] to
1946 	 * ensure confused userspace programs that start processing
1947 	 * from argv[1] won't end up walking envp. See also
1948 	 * bprm_stack_limits().
1949 	 */
1950 	if (bprm->argc == 0) {
1951 		retval = copy_string_kernel("", bprm);
1952 		if (retval < 0)
1953 			return retval;
1954 		bprm->argc = 1;
1955 
1956 		pr_warn_once("process '%s' launched '%s' with NULL argv: empty string added\n",
1957 			     current->comm, bprm->filename);
1958 	}
1959 
1960 	return bprm_execve(bprm);
1961 }
1962 
1963 int kernel_execve(const char *kernel_filename,
1964 		  const char *const *argv, const char *const *envp)
1965 {
1966 	int retval;
1967 
1968 	/* It is non-sense for kernel threads to call execve */
1969 	if (WARN_ON_ONCE(current->flags & PF_KTHREAD))
1970 		return -EINVAL;
1971 
1972 	CLASS(filename_kernel, filename)(kernel_filename);
1973 	CLASS(bprm, bprm)(AT_FDCWD, filename, 0);
1974 	if (IS_ERR(bprm))
1975 		return PTR_ERR(bprm);
1976 
1977 	retval = count_strings_kernel(argv);
1978 	if (WARN_ON_ONCE(retval == 0))
1979 		return -EINVAL;
1980 	if (retval < 0)
1981 		return retval;
1982 	bprm->argc = retval;
1983 
1984 	retval = count_strings_kernel(envp);
1985 	if (retval < 0)
1986 		return retval;
1987 	bprm->envc = retval;
1988 
1989 	retval = bprm_stack_limits(bprm);
1990 	if (retval < 0)
1991 		return retval;
1992 
1993 	retval = copy_string_kernel(bprm->filename, bprm);
1994 	if (retval < 0)
1995 		return retval;
1996 	bprm->exec = bprm->p;
1997 
1998 	retval = copy_strings_kernel(bprm->envc, envp, bprm);
1999 	if (retval < 0)
2000 		return retval;
2001 
2002 	retval = copy_strings_kernel(bprm->argc, argv, bprm);
2003 	if (retval < 0)
2004 		return retval;
2005 
2006 	return bprm_execve(bprm);
2007 }
2008 
2009 void set_binfmt(struct linux_binfmt *new)
2010 {
2011 	struct mm_struct *mm = current->mm;
2012 
2013 	if (mm->binfmt)
2014 		module_put(mm->binfmt->module);
2015 
2016 	mm->binfmt = new;
2017 	if (new)
2018 		__module_get(new->module);
2019 }
2020 EXPORT_SYMBOL(set_binfmt);
2021 
2022 static inline struct user_arg_ptr native_arg(const char __user *const __user *p)
2023 {
2024 	return (struct user_arg_ptr){.ptr.native = p};
2025 }
2026 
2027 SYSCALL_DEFINE3(execve,
2028 		const char __user *, filename,
2029 		const char __user *const __user *, argv,
2030 		const char __user *const __user *, envp)
2031 {
2032 	CLASS(filename, name)(filename);
2033 	return do_execveat_common(AT_FDCWD, name,
2034 				  native_arg(argv), native_arg(envp), 0);
2035 }
2036 
2037 SYSCALL_DEFINE5(execveat,
2038 		int, fd, const char __user *, filename,
2039 		const char __user *const __user *, argv,
2040 		const char __user *const __user *, envp,
2041 		int, flags)
2042 {
2043 	CLASS(filename_uflags, name)(filename, flags);
2044 	return do_execveat_common(fd, name,
2045 				  native_arg(argv), native_arg(envp), flags);
2046 }
2047 
2048 #ifdef CONFIG_COMPAT
2049 
2050 static inline struct user_arg_ptr compat_arg(const compat_uptr_t __user *p)
2051 {
2052 	return (struct user_arg_ptr){.is_compat = true, .ptr.compat = p};
2053 }
2054 
2055 COMPAT_SYSCALL_DEFINE3(execve, const char __user *, filename,
2056 	const compat_uptr_t __user *, argv,
2057 	const compat_uptr_t __user *, envp)
2058 {
2059 	CLASS(filename, name)(filename);
2060 	return do_execveat_common(AT_FDCWD, name,
2061 				  compat_arg(argv), compat_arg(envp), 0);
2062 }
2063 
2064 COMPAT_SYSCALL_DEFINE5(execveat, int, fd,
2065 		       const char __user *, filename,
2066 		       const compat_uptr_t __user *, argv,
2067 		       const compat_uptr_t __user *, envp,
2068 		       int,  flags)
2069 {
2070 	CLASS(filename_uflags, name)(filename, flags);
2071 	return do_execveat_common(fd, name,
2072 				  compat_arg(argv), compat_arg(envp), flags);
2073 }
2074 #endif
2075 
2076 #ifdef CONFIG_SYSCTL
2077 
2078 static int proc_dointvec_minmax_coredump(const struct ctl_table *table, int write,
2079 		void *buffer, size_t *lenp, loff_t *ppos)
2080 {
2081 	int error, old = READ_ONCE(suid_dumpable);
2082 
2083 	error = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
2084 
2085 	if (!error && write && (old != READ_ONCE(suid_dumpable)))
2086 		validate_coredump_safety();
2087 	return error;
2088 }
2089 
2090 static const struct ctl_table fs_exec_sysctls[] = {
2091 	{
2092 		.procname	= "suid_dumpable",
2093 		.data		= &suid_dumpable,
2094 		.maxlen		= sizeof(int),
2095 		.mode		= 0644,
2096 		.proc_handler	= proc_dointvec_minmax_coredump,
2097 		.extra1		= SYSCTL_ZERO,
2098 		.extra2		= SYSCTL_TWO,
2099 	},
2100 };
2101 
2102 static int __init init_fs_exec_sysctls(void)
2103 {
2104 	register_sysctl_init("fs", fs_exec_sysctls);
2105 	return 0;
2106 }
2107 
2108 fs_initcall(init_fs_exec_sysctls);
2109 #endif /* CONFIG_SYSCTL */
2110 
2111 #ifdef CONFIG_EXEC_KUNIT_TEST
2112 #include "tests/exec_kunit.c"
2113 #endif
2114