xref: /openbmc/linux/fs/coredump.c (revision d15cb3da)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/slab.h>
3 #include <linux/file.h>
4 #include <linux/fdtable.h>
5 #include <linux/freezer.h>
6 #include <linux/mm.h>
7 #include <linux/stat.h>
8 #include <linux/fcntl.h>
9 #include <linux/swap.h>
10 #include <linux/ctype.h>
11 #include <linux/string.h>
12 #include <linux/init.h>
13 #include <linux/pagemap.h>
14 #include <linux/perf_event.h>
15 #include <linux/highmem.h>
16 #include <linux/spinlock.h>
17 #include <linux/key.h>
18 #include <linux/personality.h>
19 #include <linux/binfmts.h>
20 #include <linux/coredump.h>
21 #include <linux/sched/coredump.h>
22 #include <linux/sched/signal.h>
23 #include <linux/sched/task_stack.h>
24 #include <linux/utsname.h>
25 #include <linux/pid_namespace.h>
26 #include <linux/module.h>
27 #include <linux/namei.h>
28 #include <linux/mount.h>
29 #include <linux/security.h>
30 #include <linux/syscalls.h>
31 #include <linux/tsacct_kern.h>
32 #include <linux/cn_proc.h>
33 #include <linux/audit.h>
34 #include <linux/tracehook.h>
35 #include <linux/kmod.h>
36 #include <linux/fsnotify.h>
37 #include <linux/fs_struct.h>
38 #include <linux/pipe_fs_i.h>
39 #include <linux/oom.h>
40 #include <linux/compat.h>
41 #include <linux/fs.h>
42 #include <linux/path.h>
43 #include <linux/timekeeping.h>
44 #include <linux/sysctl.h>
45 
46 #include <linux/uaccess.h>
47 #include <asm/mmu_context.h>
48 #include <asm/tlb.h>
49 #include <asm/exec.h>
50 
51 #include <trace/events/task.h>
52 #include "internal.h"
53 
54 #include <trace/events/sched.h>
55 
56 static int core_uses_pid;
57 static unsigned int core_pipe_limit;
58 static char core_pattern[CORENAME_MAX_SIZE] = "core";
59 static int core_name_size = CORENAME_MAX_SIZE;
60 
61 struct core_name {
62 	char *corename;
63 	int used, size;
64 };
65 
66 static int expand_corename(struct core_name *cn, int size)
67 {
68 	char *corename = krealloc(cn->corename, size, GFP_KERNEL);
69 
70 	if (!corename)
71 		return -ENOMEM;
72 
73 	if (size > core_name_size) /* racy but harmless */
74 		core_name_size = size;
75 
76 	cn->size = ksize(corename);
77 	cn->corename = corename;
78 	return 0;
79 }
80 
81 static __printf(2, 0) int cn_vprintf(struct core_name *cn, const char *fmt,
82 				     va_list arg)
83 {
84 	int free, need;
85 	va_list arg_copy;
86 
87 again:
88 	free = cn->size - cn->used;
89 
90 	va_copy(arg_copy, arg);
91 	need = vsnprintf(cn->corename + cn->used, free, fmt, arg_copy);
92 	va_end(arg_copy);
93 
94 	if (need < free) {
95 		cn->used += need;
96 		return 0;
97 	}
98 
99 	if (!expand_corename(cn, cn->size + need - free + 1))
100 		goto again;
101 
102 	return -ENOMEM;
103 }
104 
105 static __printf(2, 3) int cn_printf(struct core_name *cn, const char *fmt, ...)
106 {
107 	va_list arg;
108 	int ret;
109 
110 	va_start(arg, fmt);
111 	ret = cn_vprintf(cn, fmt, arg);
112 	va_end(arg);
113 
114 	return ret;
115 }
116 
117 static __printf(2, 3)
118 int cn_esc_printf(struct core_name *cn, const char *fmt, ...)
119 {
120 	int cur = cn->used;
121 	va_list arg;
122 	int ret;
123 
124 	va_start(arg, fmt);
125 	ret = cn_vprintf(cn, fmt, arg);
126 	va_end(arg);
127 
128 	if (ret == 0) {
129 		/*
130 		 * Ensure that this coredump name component can't cause the
131 		 * resulting corefile path to consist of a ".." or ".".
132 		 */
133 		if ((cn->used - cur == 1 && cn->corename[cur] == '.') ||
134 				(cn->used - cur == 2 && cn->corename[cur] == '.'
135 				&& cn->corename[cur+1] == '.'))
136 			cn->corename[cur] = '!';
137 
138 		/*
139 		 * Empty names are fishy and could be used to create a "//" in a
140 		 * corefile name, causing the coredump to happen one directory
141 		 * level too high. Enforce that all components of the core
142 		 * pattern are at least one character long.
143 		 */
144 		if (cn->used == cur)
145 			ret = cn_printf(cn, "!");
146 	}
147 
148 	for (; cur < cn->used; ++cur) {
149 		if (cn->corename[cur] == '/')
150 			cn->corename[cur] = '!';
151 	}
152 	return ret;
153 }
154 
155 static int cn_print_exe_file(struct core_name *cn, bool name_only)
156 {
157 	struct file *exe_file;
158 	char *pathbuf, *path, *ptr;
159 	int ret;
160 
161 	exe_file = get_mm_exe_file(current->mm);
162 	if (!exe_file)
163 		return cn_esc_printf(cn, "%s (path unknown)", current->comm);
164 
165 	pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
166 	if (!pathbuf) {
167 		ret = -ENOMEM;
168 		goto put_exe_file;
169 	}
170 
171 	path = file_path(exe_file, pathbuf, PATH_MAX);
172 	if (IS_ERR(path)) {
173 		ret = PTR_ERR(path);
174 		goto free_buf;
175 	}
176 
177 	if (name_only) {
178 		ptr = strrchr(path, '/');
179 		if (ptr)
180 			path = ptr + 1;
181 	}
182 	ret = cn_esc_printf(cn, "%s", path);
183 
184 free_buf:
185 	kfree(pathbuf);
186 put_exe_file:
187 	fput(exe_file);
188 	return ret;
189 }
190 
191 /* format_corename will inspect the pattern parameter, and output a
192  * name into corename, which must have space for at least
193  * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
194  */
195 static int format_corename(struct core_name *cn, struct coredump_params *cprm,
196 			   size_t **argv, int *argc)
197 {
198 	const struct cred *cred = current_cred();
199 	const char *pat_ptr = core_pattern;
200 	int ispipe = (*pat_ptr == '|');
201 	bool was_space = false;
202 	int pid_in_pattern = 0;
203 	int err = 0;
204 
205 	cn->used = 0;
206 	cn->corename = NULL;
207 	if (expand_corename(cn, core_name_size))
208 		return -ENOMEM;
209 	cn->corename[0] = '\0';
210 
211 	if (ispipe) {
212 		int argvs = sizeof(core_pattern) / 2;
213 		(*argv) = kmalloc_array(argvs, sizeof(**argv), GFP_KERNEL);
214 		if (!(*argv))
215 			return -ENOMEM;
216 		(*argv)[(*argc)++] = 0;
217 		++pat_ptr;
218 		if (!(*pat_ptr))
219 			return -ENOMEM;
220 	}
221 
222 	/* Repeat as long as we have more pattern to process and more output
223 	   space */
224 	while (*pat_ptr) {
225 		/*
226 		 * Split on spaces before doing template expansion so that
227 		 * %e and %E don't get split if they have spaces in them
228 		 */
229 		if (ispipe) {
230 			if (isspace(*pat_ptr)) {
231 				if (cn->used != 0)
232 					was_space = true;
233 				pat_ptr++;
234 				continue;
235 			} else if (was_space) {
236 				was_space = false;
237 				err = cn_printf(cn, "%c", '\0');
238 				if (err)
239 					return err;
240 				(*argv)[(*argc)++] = cn->used;
241 			}
242 		}
243 		if (*pat_ptr != '%') {
244 			err = cn_printf(cn, "%c", *pat_ptr++);
245 		} else {
246 			switch (*++pat_ptr) {
247 			/* single % at the end, drop that */
248 			case 0:
249 				goto out;
250 			/* Double percent, output one percent */
251 			case '%':
252 				err = cn_printf(cn, "%c", '%');
253 				break;
254 			/* pid */
255 			case 'p':
256 				pid_in_pattern = 1;
257 				err = cn_printf(cn, "%d",
258 					      task_tgid_vnr(current));
259 				break;
260 			/* global pid */
261 			case 'P':
262 				err = cn_printf(cn, "%d",
263 					      task_tgid_nr(current));
264 				break;
265 			case 'i':
266 				err = cn_printf(cn, "%d",
267 					      task_pid_vnr(current));
268 				break;
269 			case 'I':
270 				err = cn_printf(cn, "%d",
271 					      task_pid_nr(current));
272 				break;
273 			/* uid */
274 			case 'u':
275 				err = cn_printf(cn, "%u",
276 						from_kuid(&init_user_ns,
277 							  cred->uid));
278 				break;
279 			/* gid */
280 			case 'g':
281 				err = cn_printf(cn, "%u",
282 						from_kgid(&init_user_ns,
283 							  cred->gid));
284 				break;
285 			case 'd':
286 				err = cn_printf(cn, "%d",
287 					__get_dumpable(cprm->mm_flags));
288 				break;
289 			/* signal that caused the coredump */
290 			case 's':
291 				err = cn_printf(cn, "%d",
292 						cprm->siginfo->si_signo);
293 				break;
294 			/* UNIX time of coredump */
295 			case 't': {
296 				time64_t time;
297 
298 				time = ktime_get_real_seconds();
299 				err = cn_printf(cn, "%lld", time);
300 				break;
301 			}
302 			/* hostname */
303 			case 'h':
304 				down_read(&uts_sem);
305 				err = cn_esc_printf(cn, "%s",
306 					      utsname()->nodename);
307 				up_read(&uts_sem);
308 				break;
309 			/* executable, could be changed by prctl PR_SET_NAME etc */
310 			case 'e':
311 				err = cn_esc_printf(cn, "%s", current->comm);
312 				break;
313 			/* file name of executable */
314 			case 'f':
315 				err = cn_print_exe_file(cn, true);
316 				break;
317 			case 'E':
318 				err = cn_print_exe_file(cn, false);
319 				break;
320 			/* core limit size */
321 			case 'c':
322 				err = cn_printf(cn, "%lu",
323 					      rlimit(RLIMIT_CORE));
324 				break;
325 			default:
326 				break;
327 			}
328 			++pat_ptr;
329 		}
330 
331 		if (err)
332 			return err;
333 	}
334 
335 out:
336 	/* Backward compatibility with core_uses_pid:
337 	 *
338 	 * If core_pattern does not include a %p (as is the default)
339 	 * and core_uses_pid is set, then .%pid will be appended to
340 	 * the filename. Do not do this for piped commands. */
341 	if (!ispipe && !pid_in_pattern && core_uses_pid) {
342 		err = cn_printf(cn, ".%d", task_tgid_vnr(current));
343 		if (err)
344 			return err;
345 	}
346 	return ispipe;
347 }
348 
349 static int zap_process(struct task_struct *start, int exit_code)
350 {
351 	struct task_struct *t;
352 	int nr = 0;
353 
354 	/* ignore all signals except SIGKILL, see prepare_signal() */
355 	start->signal->flags = SIGNAL_GROUP_EXIT;
356 	start->signal->group_exit_code = exit_code;
357 	start->signal->group_stop_count = 0;
358 
359 	for_each_thread(start, t) {
360 		task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
361 		if (t != current && !(t->flags & PF_POSTCOREDUMP)) {
362 			sigaddset(&t->pending.signal, SIGKILL);
363 			signal_wake_up(t, 1);
364 			nr++;
365 		}
366 	}
367 
368 	return nr;
369 }
370 
371 static int zap_threads(struct task_struct *tsk,
372 			struct core_state *core_state, int exit_code)
373 {
374 	struct signal_struct *signal = tsk->signal;
375 	int nr = -EAGAIN;
376 
377 	spin_lock_irq(&tsk->sighand->siglock);
378 	if (!(signal->flags & SIGNAL_GROUP_EXIT) && !signal->group_exec_task) {
379 		signal->core_state = core_state;
380 		nr = zap_process(tsk, exit_code);
381 		clear_tsk_thread_flag(tsk, TIF_SIGPENDING);
382 		tsk->flags |= PF_DUMPCORE;
383 		atomic_set(&core_state->nr_threads, nr);
384 	}
385 	spin_unlock_irq(&tsk->sighand->siglock);
386 	return nr;
387 }
388 
389 static int coredump_wait(int exit_code, struct core_state *core_state)
390 {
391 	struct task_struct *tsk = current;
392 	int core_waiters = -EBUSY;
393 
394 	init_completion(&core_state->startup);
395 	core_state->dumper.task = tsk;
396 	core_state->dumper.next = NULL;
397 
398 	core_waiters = zap_threads(tsk, core_state, exit_code);
399 	if (core_waiters > 0) {
400 		struct core_thread *ptr;
401 
402 		freezer_do_not_count();
403 		wait_for_completion(&core_state->startup);
404 		freezer_count();
405 		/*
406 		 * Wait for all the threads to become inactive, so that
407 		 * all the thread context (extended register state, like
408 		 * fpu etc) gets copied to the memory.
409 		 */
410 		ptr = core_state->dumper.next;
411 		while (ptr != NULL) {
412 			wait_task_inactive(ptr->task, 0);
413 			ptr = ptr->next;
414 		}
415 	}
416 
417 	return core_waiters;
418 }
419 
420 static void coredump_finish(bool core_dumped)
421 {
422 	struct core_thread *curr, *next;
423 	struct task_struct *task;
424 
425 	spin_lock_irq(&current->sighand->siglock);
426 	if (core_dumped && !__fatal_signal_pending(current))
427 		current->signal->group_exit_code |= 0x80;
428 	next = current->signal->core_state->dumper.next;
429 	current->signal->core_state = NULL;
430 	spin_unlock_irq(&current->sighand->siglock);
431 
432 	while ((curr = next) != NULL) {
433 		next = curr->next;
434 		task = curr->task;
435 		/*
436 		 * see coredump_task_exit(), curr->task must not see
437 		 * ->task == NULL before we read ->next.
438 		 */
439 		smp_mb();
440 		curr->task = NULL;
441 		wake_up_process(task);
442 	}
443 }
444 
445 static bool dump_interrupted(void)
446 {
447 	/*
448 	 * SIGKILL or freezing() interrupt the coredumping. Perhaps we
449 	 * can do try_to_freeze() and check __fatal_signal_pending(),
450 	 * but then we need to teach dump_write() to restart and clear
451 	 * TIF_SIGPENDING.
452 	 */
453 	return fatal_signal_pending(current) || freezing(current);
454 }
455 
456 static void wait_for_dump_helpers(struct file *file)
457 {
458 	struct pipe_inode_info *pipe = file->private_data;
459 
460 	pipe_lock(pipe);
461 	pipe->readers++;
462 	pipe->writers--;
463 	wake_up_interruptible_sync(&pipe->rd_wait);
464 	kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
465 	pipe_unlock(pipe);
466 
467 	/*
468 	 * We actually want wait_event_freezable() but then we need
469 	 * to clear TIF_SIGPENDING and improve dump_interrupted().
470 	 */
471 	wait_event_interruptible(pipe->rd_wait, pipe->readers == 1);
472 
473 	pipe_lock(pipe);
474 	pipe->readers--;
475 	pipe->writers++;
476 	pipe_unlock(pipe);
477 }
478 
479 /*
480  * umh_pipe_setup
481  * helper function to customize the process used
482  * to collect the core in userspace.  Specifically
483  * it sets up a pipe and installs it as fd 0 (stdin)
484  * for the process.  Returns 0 on success, or
485  * PTR_ERR on failure.
486  * Note that it also sets the core limit to 1.  This
487  * is a special value that we use to trap recursive
488  * core dumps
489  */
490 static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
491 {
492 	struct file *files[2];
493 	struct coredump_params *cp = (struct coredump_params *)info->data;
494 	int err = create_pipe_files(files, 0);
495 	if (err)
496 		return err;
497 
498 	cp->file = files[1];
499 
500 	err = replace_fd(0, files[0], 0);
501 	fput(files[0]);
502 	/* and disallow core files too */
503 	current->signal->rlim[RLIMIT_CORE] = (struct rlimit){1, 1};
504 
505 	return err;
506 }
507 
508 void do_coredump(const kernel_siginfo_t *siginfo)
509 {
510 	struct core_state core_state;
511 	struct core_name cn;
512 	struct mm_struct *mm = current->mm;
513 	struct linux_binfmt * binfmt;
514 	const struct cred *old_cred;
515 	struct cred *cred;
516 	int retval = 0;
517 	int ispipe;
518 	size_t *argv = NULL;
519 	int argc = 0;
520 	/* require nonrelative corefile path and be extra careful */
521 	bool need_suid_safe = false;
522 	bool core_dumped = false;
523 	static atomic_t core_dump_count = ATOMIC_INIT(0);
524 	struct coredump_params cprm = {
525 		.siginfo = siginfo,
526 		.regs = signal_pt_regs(),
527 		.limit = rlimit(RLIMIT_CORE),
528 		/*
529 		 * We must use the same mm->flags while dumping core to avoid
530 		 * inconsistency of bit flags, since this flag is not protected
531 		 * by any locks.
532 		 */
533 		.mm_flags = mm->flags,
534 	};
535 
536 	audit_core_dumps(siginfo->si_signo);
537 
538 	binfmt = mm->binfmt;
539 	if (!binfmt || !binfmt->core_dump)
540 		goto fail;
541 	if (!__get_dumpable(cprm.mm_flags))
542 		goto fail;
543 
544 	cred = prepare_creds();
545 	if (!cred)
546 		goto fail;
547 	/*
548 	 * We cannot trust fsuid as being the "true" uid of the process
549 	 * nor do we know its entire history. We only know it was tainted
550 	 * so we dump it as root in mode 2, and only into a controlled
551 	 * environment (pipe handler or fully qualified path).
552 	 */
553 	if (__get_dumpable(cprm.mm_flags) == SUID_DUMP_ROOT) {
554 		/* Setuid core dump mode */
555 		cred->fsuid = GLOBAL_ROOT_UID;	/* Dump root private */
556 		need_suid_safe = true;
557 	}
558 
559 	retval = coredump_wait(siginfo->si_signo, &core_state);
560 	if (retval < 0)
561 		goto fail_creds;
562 
563 	old_cred = override_creds(cred);
564 
565 	ispipe = format_corename(&cn, &cprm, &argv, &argc);
566 
567 	if (ispipe) {
568 		int argi;
569 		int dump_count;
570 		char **helper_argv;
571 		struct subprocess_info *sub_info;
572 
573 		if (ispipe < 0) {
574 			printk(KERN_WARNING "format_corename failed\n");
575 			printk(KERN_WARNING "Aborting core\n");
576 			goto fail_unlock;
577 		}
578 
579 		if (cprm.limit == 1) {
580 			/* See umh_pipe_setup() which sets RLIMIT_CORE = 1.
581 			 *
582 			 * Normally core limits are irrelevant to pipes, since
583 			 * we're not writing to the file system, but we use
584 			 * cprm.limit of 1 here as a special value, this is a
585 			 * consistent way to catch recursive crashes.
586 			 * We can still crash if the core_pattern binary sets
587 			 * RLIM_CORE = !1, but it runs as root, and can do
588 			 * lots of stupid things.
589 			 *
590 			 * Note that we use task_tgid_vnr here to grab the pid
591 			 * of the process group leader.  That way we get the
592 			 * right pid if a thread in a multi-threaded
593 			 * core_pattern process dies.
594 			 */
595 			printk(KERN_WARNING
596 				"Process %d(%s) has RLIMIT_CORE set to 1\n",
597 				task_tgid_vnr(current), current->comm);
598 			printk(KERN_WARNING "Aborting core\n");
599 			goto fail_unlock;
600 		}
601 		cprm.limit = RLIM_INFINITY;
602 
603 		dump_count = atomic_inc_return(&core_dump_count);
604 		if (core_pipe_limit && (core_pipe_limit < dump_count)) {
605 			printk(KERN_WARNING "Pid %d(%s) over core_pipe_limit\n",
606 			       task_tgid_vnr(current), current->comm);
607 			printk(KERN_WARNING "Skipping core dump\n");
608 			goto fail_dropcount;
609 		}
610 
611 		helper_argv = kmalloc_array(argc + 1, sizeof(*helper_argv),
612 					    GFP_KERNEL);
613 		if (!helper_argv) {
614 			printk(KERN_WARNING "%s failed to allocate memory\n",
615 			       __func__);
616 			goto fail_dropcount;
617 		}
618 		for (argi = 0; argi < argc; argi++)
619 			helper_argv[argi] = cn.corename + argv[argi];
620 		helper_argv[argi] = NULL;
621 
622 		retval = -ENOMEM;
623 		sub_info = call_usermodehelper_setup(helper_argv[0],
624 						helper_argv, NULL, GFP_KERNEL,
625 						umh_pipe_setup, NULL, &cprm);
626 		if (sub_info)
627 			retval = call_usermodehelper_exec(sub_info,
628 							  UMH_WAIT_EXEC);
629 
630 		kfree(helper_argv);
631 		if (retval) {
632 			printk(KERN_INFO "Core dump to |%s pipe failed\n",
633 			       cn.corename);
634 			goto close_fail;
635 		}
636 	} else {
637 		struct user_namespace *mnt_userns;
638 		struct inode *inode;
639 		int open_flags = O_CREAT | O_RDWR | O_NOFOLLOW |
640 				 O_LARGEFILE | O_EXCL;
641 
642 		if (cprm.limit < binfmt->min_coredump)
643 			goto fail_unlock;
644 
645 		if (need_suid_safe && cn.corename[0] != '/') {
646 			printk(KERN_WARNING "Pid %d(%s) can only dump core "\
647 				"to fully qualified path!\n",
648 				task_tgid_vnr(current), current->comm);
649 			printk(KERN_WARNING "Skipping core dump\n");
650 			goto fail_unlock;
651 		}
652 
653 		/*
654 		 * Unlink the file if it exists unless this is a SUID
655 		 * binary - in that case, we're running around with root
656 		 * privs and don't want to unlink another user's coredump.
657 		 */
658 		if (!need_suid_safe) {
659 			/*
660 			 * If it doesn't exist, that's fine. If there's some
661 			 * other problem, we'll catch it at the filp_open().
662 			 */
663 			do_unlinkat(AT_FDCWD, getname_kernel(cn.corename));
664 		}
665 
666 		/*
667 		 * There is a race between unlinking and creating the
668 		 * file, but if that causes an EEXIST here, that's
669 		 * fine - another process raced with us while creating
670 		 * the corefile, and the other process won. To userspace,
671 		 * what matters is that at least one of the two processes
672 		 * writes its coredump successfully, not which one.
673 		 */
674 		if (need_suid_safe) {
675 			/*
676 			 * Using user namespaces, normal user tasks can change
677 			 * their current->fs->root to point to arbitrary
678 			 * directories. Since the intention of the "only dump
679 			 * with a fully qualified path" rule is to control where
680 			 * coredumps may be placed using root privileges,
681 			 * current->fs->root must not be used. Instead, use the
682 			 * root directory of init_task.
683 			 */
684 			struct path root;
685 
686 			task_lock(&init_task);
687 			get_fs_root(init_task.fs, &root);
688 			task_unlock(&init_task);
689 			cprm.file = file_open_root(&root, cn.corename,
690 						   open_flags, 0600);
691 			path_put(&root);
692 		} else {
693 			cprm.file = filp_open(cn.corename, open_flags, 0600);
694 		}
695 		if (IS_ERR(cprm.file))
696 			goto fail_unlock;
697 
698 		inode = file_inode(cprm.file);
699 		if (inode->i_nlink > 1)
700 			goto close_fail;
701 		if (d_unhashed(cprm.file->f_path.dentry))
702 			goto close_fail;
703 		/*
704 		 * AK: actually i see no reason to not allow this for named
705 		 * pipes etc, but keep the previous behaviour for now.
706 		 */
707 		if (!S_ISREG(inode->i_mode))
708 			goto close_fail;
709 		/*
710 		 * Don't dump core if the filesystem changed owner or mode
711 		 * of the file during file creation. This is an issue when
712 		 * a process dumps core while its cwd is e.g. on a vfat
713 		 * filesystem.
714 		 */
715 		mnt_userns = file_mnt_user_ns(cprm.file);
716 		if (!uid_eq(i_uid_into_mnt(mnt_userns, inode),
717 			    current_fsuid())) {
718 			pr_info_ratelimited("Core dump to %s aborted: cannot preserve file owner\n",
719 					    cn.corename);
720 			goto close_fail;
721 		}
722 		if ((inode->i_mode & 0677) != 0600) {
723 			pr_info_ratelimited("Core dump to %s aborted: cannot preserve file permissions\n",
724 					    cn.corename);
725 			goto close_fail;
726 		}
727 		if (!(cprm.file->f_mode & FMODE_CAN_WRITE))
728 			goto close_fail;
729 		if (do_truncate(mnt_userns, cprm.file->f_path.dentry,
730 				0, 0, cprm.file))
731 			goto close_fail;
732 	}
733 
734 	/* get us an unshared descriptor table; almost always a no-op */
735 	/* The cell spufs coredump code reads the file descriptor tables */
736 	retval = unshare_files();
737 	if (retval)
738 		goto close_fail;
739 	if (!dump_interrupted()) {
740 		/*
741 		 * umh disabled with CONFIG_STATIC_USERMODEHELPER_PATH="" would
742 		 * have this set to NULL.
743 		 */
744 		if (!cprm.file) {
745 			pr_info("Core dump to |%s disabled\n", cn.corename);
746 			goto close_fail;
747 		}
748 		file_start_write(cprm.file);
749 		core_dumped = binfmt->core_dump(&cprm);
750 		/*
751 		 * Ensures that file size is big enough to contain the current
752 		 * file postion. This prevents gdb from complaining about
753 		 * a truncated file if the last "write" to the file was
754 		 * dump_skip.
755 		 */
756 		if (cprm.to_skip) {
757 			cprm.to_skip--;
758 			dump_emit(&cprm, "", 1);
759 		}
760 		file_end_write(cprm.file);
761 	}
762 	if (ispipe && core_pipe_limit)
763 		wait_for_dump_helpers(cprm.file);
764 close_fail:
765 	if (cprm.file)
766 		filp_close(cprm.file, NULL);
767 fail_dropcount:
768 	if (ispipe)
769 		atomic_dec(&core_dump_count);
770 fail_unlock:
771 	kfree(argv);
772 	kfree(cn.corename);
773 	coredump_finish(core_dumped);
774 	revert_creds(old_cred);
775 fail_creds:
776 	put_cred(cred);
777 fail:
778 	return;
779 }
780 
781 /*
782  * Core dumping helper functions.  These are the only things you should
783  * do on a core-file: use only these functions to write out all the
784  * necessary info.
785  */
786 static int __dump_emit(struct coredump_params *cprm, const void *addr, int nr)
787 {
788 	struct file *file = cprm->file;
789 	loff_t pos = file->f_pos;
790 	ssize_t n;
791 	if (cprm->written + nr > cprm->limit)
792 		return 0;
793 
794 
795 	if (dump_interrupted())
796 		return 0;
797 	n = __kernel_write(file, addr, nr, &pos);
798 	if (n != nr)
799 		return 0;
800 	file->f_pos = pos;
801 	cprm->written += n;
802 	cprm->pos += n;
803 
804 	return 1;
805 }
806 
807 static int __dump_skip(struct coredump_params *cprm, size_t nr)
808 {
809 	static char zeroes[PAGE_SIZE];
810 	struct file *file = cprm->file;
811 	if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
812 		if (dump_interrupted() ||
813 		    file->f_op->llseek(file, nr, SEEK_CUR) < 0)
814 			return 0;
815 		cprm->pos += nr;
816 		return 1;
817 	} else {
818 		while (nr > PAGE_SIZE) {
819 			if (!__dump_emit(cprm, zeroes, PAGE_SIZE))
820 				return 0;
821 			nr -= PAGE_SIZE;
822 		}
823 		return __dump_emit(cprm, zeroes, nr);
824 	}
825 }
826 
827 int dump_emit(struct coredump_params *cprm, const void *addr, int nr)
828 {
829 	if (cprm->to_skip) {
830 		if (!__dump_skip(cprm, cprm->to_skip))
831 			return 0;
832 		cprm->to_skip = 0;
833 	}
834 	return __dump_emit(cprm, addr, nr);
835 }
836 EXPORT_SYMBOL(dump_emit);
837 
838 void dump_skip_to(struct coredump_params *cprm, unsigned long pos)
839 {
840 	cprm->to_skip = pos - cprm->pos;
841 }
842 EXPORT_SYMBOL(dump_skip_to);
843 
844 void dump_skip(struct coredump_params *cprm, size_t nr)
845 {
846 	cprm->to_skip += nr;
847 }
848 EXPORT_SYMBOL(dump_skip);
849 
850 #ifdef CONFIG_ELF_CORE
851 int dump_user_range(struct coredump_params *cprm, unsigned long start,
852 		    unsigned long len)
853 {
854 	unsigned long addr;
855 
856 	for (addr = start; addr < start + len; addr += PAGE_SIZE) {
857 		struct page *page;
858 		int stop;
859 
860 		/*
861 		 * To avoid having to allocate page tables for virtual address
862 		 * ranges that have never been used yet, and also to make it
863 		 * easy to generate sparse core files, use a helper that returns
864 		 * NULL when encountering an empty page table entry that would
865 		 * otherwise have been filled with the zero page.
866 		 */
867 		page = get_dump_page(addr);
868 		if (page) {
869 			void *kaddr = kmap_local_page(page);
870 
871 			stop = !dump_emit(cprm, kaddr, PAGE_SIZE);
872 			kunmap_local(kaddr);
873 			put_page(page);
874 			if (stop)
875 				return 0;
876 		} else {
877 			dump_skip(cprm, PAGE_SIZE);
878 		}
879 	}
880 	return 1;
881 }
882 #endif
883 
884 int dump_align(struct coredump_params *cprm, int align)
885 {
886 	unsigned mod = (cprm->pos + cprm->to_skip) & (align - 1);
887 	if (align & (align - 1))
888 		return 0;
889 	if (mod)
890 		cprm->to_skip += align - mod;
891 	return 1;
892 }
893 EXPORT_SYMBOL(dump_align);
894 
895 #ifdef CONFIG_SYSCTL
896 
897 void validate_coredump_safety(void)
898 {
899 	if (suid_dumpable == SUID_DUMP_ROOT &&
900 	    core_pattern[0] != '/' && core_pattern[0] != '|') {
901 		pr_warn(
902 "Unsafe core_pattern used with fs.suid_dumpable=2.\n"
903 "Pipe handler or fully qualified core dump path required.\n"
904 "Set kernel.core_pattern before fs.suid_dumpable.\n"
905 		);
906 	}
907 }
908 
909 static int proc_dostring_coredump(struct ctl_table *table, int write,
910 		  void *buffer, size_t *lenp, loff_t *ppos)
911 {
912 	int error = proc_dostring(table, write, buffer, lenp, ppos);
913 
914 	if (!error)
915 		validate_coredump_safety();
916 	return error;
917 }
918 
919 static struct ctl_table coredump_sysctls[] = {
920 	{
921 		.procname	= "core_uses_pid",
922 		.data		= &core_uses_pid,
923 		.maxlen		= sizeof(int),
924 		.mode		= 0644,
925 		.proc_handler	= proc_dointvec,
926 	},
927 	{
928 		.procname	= "core_pattern",
929 		.data		= core_pattern,
930 		.maxlen		= CORENAME_MAX_SIZE,
931 		.mode		= 0644,
932 		.proc_handler	= proc_dostring_coredump,
933 	},
934 	{
935 		.procname	= "core_pipe_limit",
936 		.data		= &core_pipe_limit,
937 		.maxlen		= sizeof(unsigned int),
938 		.mode		= 0644,
939 		.proc_handler	= proc_dointvec,
940 	},
941 	{ }
942 };
943 
944 static int __init init_fs_coredump_sysctls(void)
945 {
946 	register_sysctl_init("kernel", coredump_sysctls);
947 	return 0;
948 }
949 fs_initcall(init_fs_coredump_sysctls);
950 #endif /* CONFIG_SYSCTL */
951 
952 /*
953  * The purpose of always_dump_vma() is to make sure that special kernel mappings
954  * that are useful for post-mortem analysis are included in every core dump.
955  * In that way we ensure that the core dump is fully interpretable later
956  * without matching up the same kernel and hardware config to see what PC values
957  * meant. These special mappings include - vDSO, vsyscall, and other
958  * architecture specific mappings
959  */
960 static bool always_dump_vma(struct vm_area_struct *vma)
961 {
962 	/* Any vsyscall mappings? */
963 	if (vma == get_gate_vma(vma->vm_mm))
964 		return true;
965 
966 	/*
967 	 * Assume that all vmas with a .name op should always be dumped.
968 	 * If this changes, a new vm_ops field can easily be added.
969 	 */
970 	if (vma->vm_ops && vma->vm_ops->name && vma->vm_ops->name(vma))
971 		return true;
972 
973 	/*
974 	 * arch_vma_name() returns non-NULL for special architecture mappings,
975 	 * such as vDSO sections.
976 	 */
977 	if (arch_vma_name(vma))
978 		return true;
979 
980 	return false;
981 }
982 
983 /*
984  * Decide how much of @vma's contents should be included in a core dump.
985  */
986 static unsigned long vma_dump_size(struct vm_area_struct *vma,
987 				   unsigned long mm_flags)
988 {
989 #define FILTER(type)	(mm_flags & (1UL << MMF_DUMP_##type))
990 
991 	/* always dump the vdso and vsyscall sections */
992 	if (always_dump_vma(vma))
993 		goto whole;
994 
995 	if (vma->vm_flags & VM_DONTDUMP)
996 		return 0;
997 
998 	/* support for DAX */
999 	if (vma_is_dax(vma)) {
1000 		if ((vma->vm_flags & VM_SHARED) && FILTER(DAX_SHARED))
1001 			goto whole;
1002 		if (!(vma->vm_flags & VM_SHARED) && FILTER(DAX_PRIVATE))
1003 			goto whole;
1004 		return 0;
1005 	}
1006 
1007 	/* Hugetlb memory check */
1008 	if (is_vm_hugetlb_page(vma)) {
1009 		if ((vma->vm_flags & VM_SHARED) && FILTER(HUGETLB_SHARED))
1010 			goto whole;
1011 		if (!(vma->vm_flags & VM_SHARED) && FILTER(HUGETLB_PRIVATE))
1012 			goto whole;
1013 		return 0;
1014 	}
1015 
1016 	/* Do not dump I/O mapped devices or special mappings */
1017 	if (vma->vm_flags & VM_IO)
1018 		return 0;
1019 
1020 	/* By default, dump shared memory if mapped from an anonymous file. */
1021 	if (vma->vm_flags & VM_SHARED) {
1022 		if (file_inode(vma->vm_file)->i_nlink == 0 ?
1023 		    FILTER(ANON_SHARED) : FILTER(MAPPED_SHARED))
1024 			goto whole;
1025 		return 0;
1026 	}
1027 
1028 	/* Dump segments that have been written to.  */
1029 	if ((!IS_ENABLED(CONFIG_MMU) || vma->anon_vma) && FILTER(ANON_PRIVATE))
1030 		goto whole;
1031 	if (vma->vm_file == NULL)
1032 		return 0;
1033 
1034 	if (FILTER(MAPPED_PRIVATE))
1035 		goto whole;
1036 
1037 	/*
1038 	 * If this is the beginning of an executable file mapping,
1039 	 * dump the first page to aid in determining what was mapped here.
1040 	 */
1041 	if (FILTER(ELF_HEADERS) &&
1042 	    vma->vm_pgoff == 0 && (vma->vm_flags & VM_READ) &&
1043 	    (READ_ONCE(file_inode(vma->vm_file)->i_mode) & 0111) != 0)
1044 		return PAGE_SIZE;
1045 
1046 #undef	FILTER
1047 
1048 	return 0;
1049 
1050 whole:
1051 	return vma->vm_end - vma->vm_start;
1052 }
1053 
1054 static struct vm_area_struct *first_vma(struct task_struct *tsk,
1055 					struct vm_area_struct *gate_vma)
1056 {
1057 	struct vm_area_struct *ret = tsk->mm->mmap;
1058 
1059 	if (ret)
1060 		return ret;
1061 	return gate_vma;
1062 }
1063 
1064 /*
1065  * Helper function for iterating across a vma list.  It ensures that the caller
1066  * will visit `gate_vma' prior to terminating the search.
1067  */
1068 static struct vm_area_struct *next_vma(struct vm_area_struct *this_vma,
1069 				       struct vm_area_struct *gate_vma)
1070 {
1071 	struct vm_area_struct *ret;
1072 
1073 	ret = this_vma->vm_next;
1074 	if (ret)
1075 		return ret;
1076 	if (this_vma == gate_vma)
1077 		return NULL;
1078 	return gate_vma;
1079 }
1080 
1081 /*
1082  * Under the mmap_lock, take a snapshot of relevant information about the task's
1083  * VMAs.
1084  */
1085 int dump_vma_snapshot(struct coredump_params *cprm, int *vma_count,
1086 		      struct core_vma_metadata **vma_meta,
1087 		      size_t *vma_data_size_ptr)
1088 {
1089 	struct vm_area_struct *vma, *gate_vma;
1090 	struct mm_struct *mm = current->mm;
1091 	int i;
1092 	size_t vma_data_size = 0;
1093 
1094 	/*
1095 	 * Once the stack expansion code is fixed to not change VMA bounds
1096 	 * under mmap_lock in read mode, this can be changed to take the
1097 	 * mmap_lock in read mode.
1098 	 */
1099 	if (mmap_write_lock_killable(mm))
1100 		return -EINTR;
1101 
1102 	gate_vma = get_gate_vma(mm);
1103 	*vma_count = mm->map_count + (gate_vma ? 1 : 0);
1104 
1105 	*vma_meta = kvmalloc_array(*vma_count, sizeof(**vma_meta), GFP_KERNEL);
1106 	if (!*vma_meta) {
1107 		mmap_write_unlock(mm);
1108 		return -ENOMEM;
1109 	}
1110 
1111 	for (i = 0, vma = first_vma(current, gate_vma); vma != NULL;
1112 			vma = next_vma(vma, gate_vma), i++) {
1113 		struct core_vma_metadata *m = (*vma_meta) + i;
1114 
1115 		m->start = vma->vm_start;
1116 		m->end = vma->vm_end;
1117 		m->flags = vma->vm_flags;
1118 		m->dump_size = vma_dump_size(vma, cprm->mm_flags);
1119 
1120 		vma_data_size += m->dump_size;
1121 	}
1122 
1123 	mmap_write_unlock(mm);
1124 
1125 	if (WARN_ON(i != *vma_count)) {
1126 		kvfree(*vma_meta);
1127 		return -EFAULT;
1128 	}
1129 
1130 	*vma_data_size_ptr = vma_data_size;
1131 	return 0;
1132 }
1133