1 #include <linux/slab.h>
2 #include <linux/file.h>
3 #include <linux/fdtable.h>
4 #include <linux/freezer.h>
6 #include <linux/stat.h>
7 #include <linux/fcntl.h>
8 #include <linux/swap.h>
9 #include <linux/string.h>
10 #include <linux/init.h>
11 #include <linux/pagemap.h>
12 #include <linux/perf_event.h>
13 #include <linux/highmem.h>
14 #include <linux/spinlock.h>
15 #include <linux/key.h>
16 #include <linux/personality.h>
17 #include <linux/binfmts.h>
18 #include <linux/coredump.h>
19 #include <linux/utsname.h>
20 #include <linux/pid_namespace.h>
21 #include <linux/module.h>
22 #include <linux/namei.h>
23 #include <linux/mount.h>
24 #include <linux/security.h>
25 #include <linux/syscalls.h>
26 #include <linux/tsacct_kern.h>
27 #include <linux/cn_proc.h>
28 #include <linux/audit.h>
29 #include <linux/tracehook.h>
30 #include <linux/kmod.h>
31 #include <linux/fsnotify.h>
32 #include <linux/fs_struct.h>
33 #include <linux/pipe_fs_i.h>
34 #include <linux/oom.h>
35 #include <linux/compat.h>
36 #include <linux/sched.h>
38 #include <linux/path.h>
40 #include <asm/uaccess.h>
41 #include <asm/mmu_context.h>
45 #include <trace/events/task.h>
48 #include <trace/events/sched.h>
51 unsigned int core_pipe_limit;
52 char core_pattern[CORENAME_MAX_SIZE] = "core";
53 static int core_name_size = CORENAME_MAX_SIZE;
60 /* The maximal length of core_pattern is also specified in sysctl.c */
62 static int expand_corename(struct core_name *cn, int size)
64 char *corename = krealloc(cn->corename, size, GFP_KERNEL);
69 if (size > core_name_size) /* racy but harmless */
70 core_name_size = size;
72 cn->size = ksize(corename);
73 cn->corename = corename;
77 static __printf(2, 0) int cn_vprintf(struct core_name *cn, const char *fmt,
84 free = cn->size - cn->used;
86 va_copy(arg_copy, arg);
87 need = vsnprintf(cn->corename + cn->used, free, fmt, arg_copy);
95 if (!expand_corename(cn, cn->size + need - free + 1))
101 static __printf(2, 3) int cn_printf(struct core_name *cn, const char *fmt, ...)
107 ret = cn_vprintf(cn, fmt, arg);
113 static __printf(2, 3)
114 int cn_esc_printf(struct core_name *cn, const char *fmt, ...)
121 ret = cn_vprintf(cn, fmt, arg);
124 for (; cur < cn->used; ++cur) {
125 if (cn->corename[cur] == '/')
126 cn->corename[cur] = '!';
131 static int cn_print_exe_file(struct core_name *cn)
133 struct file *exe_file;
134 char *pathbuf, *path;
137 exe_file = get_mm_exe_file(current->mm);
139 return cn_esc_printf(cn, "%s (path unknown)", current->comm);
141 pathbuf = kmalloc(PATH_MAX, GFP_TEMPORARY);
147 path = file_path(exe_file, pathbuf, PATH_MAX);
153 ret = cn_esc_printf(cn, "%s", path);
162 /* format_corename will inspect the pattern parameter, and output a
163 * name into corename, which must have space for at least
164 * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
166 static int format_corename(struct core_name *cn, struct coredump_params *cprm)
168 const struct cred *cred = current_cred();
169 const char *pat_ptr = core_pattern;
170 int ispipe = (*pat_ptr == '|');
171 int pid_in_pattern = 0;
176 if (expand_corename(cn, core_name_size))
178 cn->corename[0] = '\0';
183 /* Repeat as long as we have more pattern to process and more output
186 if (*pat_ptr != '%') {
187 err = cn_printf(cn, "%c", *pat_ptr++);
189 switch (*++pat_ptr) {
190 /* single % at the end, drop that */
193 /* Double percent, output one percent */
195 err = cn_printf(cn, "%c", '%');
200 err = cn_printf(cn, "%d",
201 task_tgid_vnr(current));
205 err = cn_printf(cn, "%d",
206 task_tgid_nr(current));
209 err = cn_printf(cn, "%d",
210 task_pid_vnr(current));
213 err = cn_printf(cn, "%d",
214 task_pid_nr(current));
218 err = cn_printf(cn, "%u",
219 from_kuid(&init_user_ns,
224 err = cn_printf(cn, "%u",
225 from_kgid(&init_user_ns,
229 err = cn_printf(cn, "%d",
230 __get_dumpable(cprm->mm_flags));
232 /* signal that caused the coredump */
234 err = cn_printf(cn, "%d",
235 cprm->siginfo->si_signo);
237 /* UNIX time of coredump */
240 do_gettimeofday(&tv);
241 err = cn_printf(cn, "%lu", tv.tv_sec);
247 err = cn_esc_printf(cn, "%s",
248 utsname()->nodename);
253 err = cn_esc_printf(cn, "%s", current->comm);
256 err = cn_print_exe_file(cn);
258 /* core limit size */
260 err = cn_printf(cn, "%lu",
261 rlimit(RLIMIT_CORE));
274 /* Backward compatibility with core_uses_pid:
276 * If core_pattern does not include a %p (as is the default)
277 * and core_uses_pid is set, then .%pid will be appended to
278 * the filename. Do not do this for piped commands. */
279 if (!ispipe && !pid_in_pattern && core_uses_pid) {
280 err = cn_printf(cn, ".%d", task_tgid_vnr(current));
287 static int zap_process(struct task_struct *start, int exit_code, int flags)
289 struct task_struct *t;
292 /* ignore all signals except SIGKILL, see prepare_signal() */
293 start->signal->flags = SIGNAL_GROUP_COREDUMP | flags;
294 start->signal->group_exit_code = exit_code;
295 start->signal->group_stop_count = 0;
297 for_each_thread(start, t) {
298 task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
299 if (t != current && t->mm) {
300 sigaddset(&t->pending.signal, SIGKILL);
301 signal_wake_up(t, 1);
309 static int zap_threads(struct task_struct *tsk, struct mm_struct *mm,
310 struct core_state *core_state, int exit_code)
312 struct task_struct *g, *p;
316 spin_lock_irq(&tsk->sighand->siglock);
317 if (!signal_group_exit(tsk->signal)) {
318 mm->core_state = core_state;
319 tsk->signal->group_exit_task = tsk;
320 nr = zap_process(tsk, exit_code, 0);
321 clear_tsk_thread_flag(tsk, TIF_SIGPENDING);
323 spin_unlock_irq(&tsk->sighand->siglock);
324 if (unlikely(nr < 0))
327 tsk->flags |= PF_DUMPCORE;
328 if (atomic_read(&mm->mm_users) == nr + 1)
331 * We should find and kill all tasks which use this mm, and we should
332 * count them correctly into ->nr_threads. We don't take tasklist
333 * lock, but this is safe wrt:
336 * None of sub-threads can fork after zap_process(leader). All
337 * processes which were created before this point should be
338 * visible to zap_threads() because copy_process() adds the new
339 * process to the tail of init_task.tasks list, and lock/unlock
340 * of ->siglock provides a memory barrier.
343 * The caller holds mm->mmap_sem. This means that the task which
344 * uses this mm can't pass exit_mm(), so it can't exit or clear
348 * It does list_replace_rcu(&leader->tasks, ¤t->tasks),
349 * we must see either old or new leader, this does not matter.
350 * However, it can change p->sighand, so lock_task_sighand(p)
351 * must be used. Since p->mm != NULL and we hold ->mmap_sem
354 * Note also that "g" can be the old leader with ->mm == NULL
355 * and already unhashed and thus removed from ->thread_group.
356 * This is OK, __unhash_process()->list_del_rcu() does not
357 * clear the ->next pointer, we will find the new leader via
361 for_each_process(g) {
362 if (g == tsk->group_leader)
364 if (g->flags & PF_KTHREAD)
367 for_each_thread(g, p) {
368 if (unlikely(!p->mm))
370 if (unlikely(p->mm == mm)) {
371 lock_task_sighand(p, &flags);
372 nr += zap_process(p, exit_code,
374 unlock_task_sighand(p, &flags);
381 atomic_set(&core_state->nr_threads, nr);
385 static int coredump_wait(int exit_code, struct core_state *core_state)
387 struct task_struct *tsk = current;
388 struct mm_struct *mm = tsk->mm;
389 int core_waiters = -EBUSY;
391 init_completion(&core_state->startup);
392 core_state->dumper.task = tsk;
393 core_state->dumper.next = NULL;
395 down_write(&mm->mmap_sem);
397 core_waiters = zap_threads(tsk, mm, core_state, exit_code);
398 up_write(&mm->mmap_sem);
400 if (core_waiters > 0) {
401 struct core_thread *ptr;
403 freezer_do_not_count();
404 wait_for_completion(&core_state->startup);
407 * Wait for all the threads to become inactive, so that
408 * all the thread context (extended register state, like
409 * fpu etc) gets copied to the memory.
411 ptr = core_state->dumper.next;
412 while (ptr != NULL) {
413 wait_task_inactive(ptr->task, 0);
421 static void coredump_finish(struct mm_struct *mm, bool core_dumped)
423 struct core_thread *curr, *next;
424 struct task_struct *task;
426 spin_lock_irq(¤t->sighand->siglock);
427 if (core_dumped && !__fatal_signal_pending(current))
428 current->signal->group_exit_code |= 0x80;
429 current->signal->group_exit_task = NULL;
430 current->signal->flags = SIGNAL_GROUP_EXIT;
431 spin_unlock_irq(¤t->sighand->siglock);
433 next = mm->core_state->dumper.next;
434 while ((curr = next) != NULL) {
438 * see exit_mm(), curr->task must not see
439 * ->task == NULL before we read ->next.
443 wake_up_process(task);
446 mm->core_state = NULL;
449 static bool dump_interrupted(void)
452 * SIGKILL or freezing() interrupt the coredumping. Perhaps we
453 * can do try_to_freeze() and check __fatal_signal_pending(),
454 * but then we need to teach dump_write() to restart and clear
457 return signal_pending(current);
460 static void wait_for_dump_helpers(struct file *file)
462 struct pipe_inode_info *pipe = file->private_data;
467 wake_up_interruptible_sync(&pipe->wait);
468 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
472 * We actually want wait_event_freezable() but then we need
473 * to clear TIF_SIGPENDING and improve dump_interrupted().
475 wait_event_interruptible(pipe->wait, pipe->readers == 1);
485 * helper function to customize the process used
486 * to collect the core in userspace. Specifically
487 * it sets up a pipe and installs it as fd 0 (stdin)
488 * for the process. Returns 0 on success, or
489 * PTR_ERR on failure.
490 * Note that it also sets the core limit to 1. This
491 * is a special value that we use to trap recursive
494 static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
496 struct file *files[2];
497 struct coredump_params *cp = (struct coredump_params *)info->data;
498 int err = create_pipe_files(files, 0);
504 err = replace_fd(0, files[0], 0);
506 /* and disallow core files too */
507 current->signal->rlim[RLIMIT_CORE] = (struct rlimit){1, 1};
512 void do_coredump(const siginfo_t *siginfo)
514 struct core_state core_state;
516 struct mm_struct *mm = current->mm;
517 struct linux_binfmt * binfmt;
518 const struct cred *old_cred;
522 struct files_struct *displaced;
523 /* require nonrelative corefile path and be extra careful */
524 bool need_suid_safe = false;
525 bool core_dumped = false;
526 static atomic_t core_dump_count = ATOMIC_INIT(0);
527 struct coredump_params cprm = {
529 .regs = signal_pt_regs(),
530 .limit = rlimit(RLIMIT_CORE),
532 * We must use the same mm->flags while dumping core to avoid
533 * inconsistency of bit flags, since this flag is not protected
536 .mm_flags = mm->flags,
539 audit_core_dumps(siginfo->si_signo);
542 if (!binfmt || !binfmt->core_dump)
544 if (!__get_dumpable(cprm.mm_flags))
547 cred = prepare_creds();
551 * We cannot trust fsuid as being the "true" uid of the process
552 * nor do we know its entire history. We only know it was tainted
553 * so we dump it as root in mode 2, and only into a controlled
554 * environment (pipe handler or fully qualified path).
556 if (__get_dumpable(cprm.mm_flags) == SUID_DUMP_ROOT) {
557 /* Setuid core dump mode */
558 cred->fsuid = GLOBAL_ROOT_UID; /* Dump root private */
559 need_suid_safe = true;
562 retval = coredump_wait(siginfo->si_signo, &core_state);
566 old_cred = override_creds(cred);
568 ispipe = format_corename(&cn, &cprm);
573 struct subprocess_info *sub_info;
576 printk(KERN_WARNING "format_corename failed\n");
577 printk(KERN_WARNING "Aborting core\n");
581 if (cprm.limit == 1) {
582 /* See umh_pipe_setup() which sets RLIMIT_CORE = 1.
584 * Normally core limits are irrelevant to pipes, since
585 * we're not writing to the file system, but we use
586 * cprm.limit of 1 here as a special value, this is a
587 * consistent way to catch recursive crashes.
588 * We can still crash if the core_pattern binary sets
589 * RLIM_CORE = !1, but it runs as root, and can do
590 * lots of stupid things.
592 * Note that we use task_tgid_vnr here to grab the pid
593 * of the process group leader. That way we get the
594 * right pid if a thread in a multi-threaded
595 * core_pattern process dies.
598 "Process %d(%s) has RLIMIT_CORE set to 1\n",
599 task_tgid_vnr(current), current->comm);
600 printk(KERN_WARNING "Aborting core\n");
603 cprm.limit = RLIM_INFINITY;
605 dump_count = atomic_inc_return(&core_dump_count);
606 if (core_pipe_limit && (core_pipe_limit < dump_count)) {
607 printk(KERN_WARNING "Pid %d(%s) over core_pipe_limit\n",
608 task_tgid_vnr(current), current->comm);
609 printk(KERN_WARNING "Skipping core dump\n");
613 helper_argv = argv_split(GFP_KERNEL, cn.corename, NULL);
615 printk(KERN_WARNING "%s failed to allocate memory\n",
621 sub_info = call_usermodehelper_setup(helper_argv[0],
622 helper_argv, NULL, GFP_KERNEL,
623 umh_pipe_setup, NULL, &cprm);
625 retval = call_usermodehelper_exec(sub_info,
628 argv_free(helper_argv);
630 printk(KERN_INFO "Core dump to |%s pipe failed\n",
636 int open_flags = O_CREAT | O_RDWR | O_NOFOLLOW |
637 O_LARGEFILE | O_EXCL;
639 if (cprm.limit < binfmt->min_coredump)
642 if (need_suid_safe && cn.corename[0] != '/') {
643 printk(KERN_WARNING "Pid %d(%s) can only dump core "\
644 "to fully qualified path!\n",
645 task_tgid_vnr(current), current->comm);
646 printk(KERN_WARNING "Skipping core dump\n");
651 * Unlink the file if it exists unless this is a SUID
652 * binary - in that case, we're running around with root
653 * privs and don't want to unlink another user's coredump.
655 if (!need_suid_safe) {
661 * If it doesn't exist, that's fine. If there's some
662 * other problem, we'll catch it at the filp_open().
664 (void) sys_unlink((const char __user *)cn.corename);
669 * There is a race between unlinking and creating the
670 * file, but if that causes an EEXIST here, that's
671 * fine - another process raced with us while creating
672 * the corefile, and the other process won. To userspace,
673 * what matters is that at least one of the two processes
674 * writes its coredump successfully, not which one.
676 if (need_suid_safe) {
678 * Using user namespaces, normal user tasks can change
679 * their current->fs->root to point to arbitrary
680 * directories. Since the intention of the "only dump
681 * with a fully qualified path" rule is to control where
682 * coredumps may be placed using root privileges,
683 * current->fs->root must not be used. Instead, use the
684 * root directory of init_task.
688 task_lock(&init_task);
689 get_fs_root(init_task.fs, &root);
690 task_unlock(&init_task);
691 cprm.file = file_open_root(root.dentry, root.mnt,
692 cn.corename, open_flags, 0600);
695 cprm.file = filp_open(cn.corename, open_flags, 0600);
697 if (IS_ERR(cprm.file))
700 inode = file_inode(cprm.file);
701 if (inode->i_nlink > 1)
703 if (d_unhashed(cprm.file->f_path.dentry))
706 * AK: actually i see no reason to not allow this for named
707 * pipes etc, but keep the previous behaviour for now.
709 if (!S_ISREG(inode->i_mode))
712 * Don't dump core if the filesystem changed owner or mode
713 * of the file during file creation. This is an issue when
714 * a process dumps core while its cwd is e.g. on a vfat
717 if (!uid_eq(inode->i_uid, current_fsuid()))
719 if ((inode->i_mode & 0677) != 0600)
721 if (!(cprm.file->f_mode & FMODE_CAN_WRITE))
723 if (do_truncate(cprm.file->f_path.dentry, 0, 0, cprm.file))
727 /* get us an unshared descriptor table; almost always a no-op */
728 retval = unshare_files(&displaced);
732 put_files_struct(displaced);
733 if (!dump_interrupted()) {
734 file_start_write(cprm.file);
735 core_dumped = binfmt->core_dump(&cprm);
736 file_end_write(cprm.file);
738 if (ispipe && core_pipe_limit)
739 wait_for_dump_helpers(cprm.file);
742 filp_close(cprm.file, NULL);
745 atomic_dec(&core_dump_count);
748 coredump_finish(mm, core_dumped);
749 revert_creds(old_cred);
757 * Core dumping helper functions. These are the only things you should
758 * do on a core-file: use only these functions to write out all the
761 int dump_emit(struct coredump_params *cprm, const void *addr, int nr)
763 struct file *file = cprm->file;
764 loff_t pos = file->f_pos;
766 if (cprm->written + nr > cprm->limit)
769 if (dump_interrupted())
771 n = __kernel_write(file, addr, nr, &pos);
780 EXPORT_SYMBOL(dump_emit);
782 int dump_skip(struct coredump_params *cprm, size_t nr)
784 static char zeroes[PAGE_SIZE];
785 struct file *file = cprm->file;
786 if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
787 if (cprm->written + nr > cprm->limit)
789 if (dump_interrupted() ||
790 file->f_op->llseek(file, nr, SEEK_CUR) < 0)
795 while (nr > PAGE_SIZE) {
796 if (!dump_emit(cprm, zeroes, PAGE_SIZE))
800 return dump_emit(cprm, zeroes, nr);
803 EXPORT_SYMBOL(dump_skip);
805 int dump_align(struct coredump_params *cprm, int align)
807 unsigned mod = cprm->written & (align - 1);
808 if (align & (align - 1))
810 return mod ? dump_skip(cprm, align - mod) : 1;
812 EXPORT_SYMBOL(dump_align);