Bluetooth: vhci: Fix race at creating hci device
[linux/fpc-iii.git] / fs / coredump.c
blob7eb6181184ea0f482c42c49f7a70a2d550ca8303
1 #include <linux/slab.h>
2 #include <linux/file.h>
3 #include <linux/fdtable.h>
4 #include <linux/mm.h>
5 #include <linux/stat.h>
6 #include <linux/fcntl.h>
7 #include <linux/swap.h>
8 #include <linux/string.h>
9 #include <linux/init.h>
10 #include <linux/pagemap.h>
11 #include <linux/perf_event.h>
12 #include <linux/highmem.h>
13 #include <linux/spinlock.h>
14 #include <linux/key.h>
15 #include <linux/personality.h>
16 #include <linux/binfmts.h>
17 #include <linux/coredump.h>
18 #include <linux/utsname.h>
19 #include <linux/pid_namespace.h>
20 #include <linux/module.h>
21 #include <linux/namei.h>
22 #include <linux/mount.h>
23 #include <linux/security.h>
24 #include <linux/syscalls.h>
25 #include <linux/tsacct_kern.h>
26 #include <linux/cn_proc.h>
27 #include <linux/audit.h>
28 #include <linux/tracehook.h>
29 #include <linux/kmod.h>
30 #include <linux/fsnotify.h>
31 #include <linux/fs_struct.h>
32 #include <linux/pipe_fs_i.h>
33 #include <linux/oom.h>
34 #include <linux/compat.h>
35 #include <linux/sched.h>
36 #include <linux/fs.h>
37 #include <linux/path.h>
39 #include <asm/uaccess.h>
40 #include <asm/mmu_context.h>
41 #include <asm/tlb.h>
42 #include <asm/exec.h>
44 #include <trace/events/task.h>
45 #include "internal.h"
47 #include <trace/events/sched.h>
49 int core_uses_pid;
50 unsigned int core_pipe_limit;
51 char core_pattern[CORENAME_MAX_SIZE] = "core";
52 static int core_name_size = CORENAME_MAX_SIZE;
54 struct core_name {
55 char *corename;
56 int used, size;
59 /* The maximal length of core_pattern is also specified in sysctl.c */
61 static int expand_corename(struct core_name *cn, int size)
63 char *corename = krealloc(cn->corename, size, GFP_KERNEL);
65 if (!corename)
66 return -ENOMEM;
68 if (size > core_name_size) /* racy but harmless */
69 core_name_size = size;
71 cn->size = ksize(corename);
72 cn->corename = corename;
73 return 0;
76 static int cn_vprintf(struct core_name *cn, const char *fmt, va_list arg)
78 int free, need;
79 va_list arg_copy;
81 again:
82 free = cn->size - cn->used;
84 va_copy(arg_copy, arg);
85 need = vsnprintf(cn->corename + cn->used, free, fmt, arg_copy);
86 va_end(arg_copy);
88 if (need < free) {
89 cn->used += need;
90 return 0;
93 if (!expand_corename(cn, cn->size + need - free + 1))
94 goto again;
96 return -ENOMEM;
99 static int cn_printf(struct core_name *cn, const char *fmt, ...)
101 va_list arg;
102 int ret;
104 va_start(arg, fmt);
105 ret = cn_vprintf(cn, fmt, arg);
106 va_end(arg);
108 return ret;
111 static int cn_esc_printf(struct core_name *cn, const char *fmt, ...)
113 int cur = cn->used;
114 va_list arg;
115 int ret;
117 va_start(arg, fmt);
118 ret = cn_vprintf(cn, fmt, arg);
119 va_end(arg);
121 for (; cur < cn->used; ++cur) {
122 if (cn->corename[cur] == '/')
123 cn->corename[cur] = '!';
125 return ret;
128 static int cn_print_exe_file(struct core_name *cn)
130 struct file *exe_file;
131 char *pathbuf, *path;
132 int ret;
134 exe_file = get_mm_exe_file(current->mm);
135 if (!exe_file)
136 return cn_esc_printf(cn, "%s (path unknown)", current->comm);
138 pathbuf = kmalloc(PATH_MAX, GFP_TEMPORARY);
139 if (!pathbuf) {
140 ret = -ENOMEM;
141 goto put_exe_file;
144 path = d_path(&exe_file->f_path, pathbuf, PATH_MAX);
145 if (IS_ERR(path)) {
146 ret = PTR_ERR(path);
147 goto free_buf;
150 ret = cn_esc_printf(cn, "%s", path);
152 free_buf:
153 kfree(pathbuf);
154 put_exe_file:
155 fput(exe_file);
156 return ret;
159 /* format_corename will inspect the pattern parameter, and output a
160 * name into corename, which must have space for at least
161 * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
163 static int format_corename(struct core_name *cn, struct coredump_params *cprm)
165 const struct cred *cred = current_cred();
166 const char *pat_ptr = core_pattern;
167 int ispipe = (*pat_ptr == '|');
168 int pid_in_pattern = 0;
169 int err = 0;
171 cn->used = 0;
172 cn->corename = NULL;
173 if (expand_corename(cn, core_name_size))
174 return -ENOMEM;
175 cn->corename[0] = '\0';
177 if (ispipe)
178 ++pat_ptr;
180 /* Repeat as long as we have more pattern to process and more output
181 space */
182 while (*pat_ptr) {
183 if (*pat_ptr != '%') {
184 err = cn_printf(cn, "%c", *pat_ptr++);
185 } else {
186 switch (*++pat_ptr) {
187 /* single % at the end, drop that */
188 case 0:
189 goto out;
190 /* Double percent, output one percent */
191 case '%':
192 err = cn_printf(cn, "%c", '%');
193 break;
194 /* pid */
195 case 'p':
196 pid_in_pattern = 1;
197 err = cn_printf(cn, "%d",
198 task_tgid_vnr(current));
199 break;
200 /* global pid */
201 case 'P':
202 err = cn_printf(cn, "%d",
203 task_tgid_nr(current));
204 break;
205 case 'i':
206 err = cn_printf(cn, "%d",
207 task_pid_vnr(current));
208 break;
209 case 'I':
210 err = cn_printf(cn, "%d",
211 task_pid_nr(current));
212 break;
213 /* uid */
214 case 'u':
215 err = cn_printf(cn, "%d", cred->uid);
216 break;
217 /* gid */
218 case 'g':
219 err = cn_printf(cn, "%d", cred->gid);
220 break;
221 case 'd':
222 err = cn_printf(cn, "%d",
223 __get_dumpable(cprm->mm_flags));
224 break;
225 /* signal that caused the coredump */
226 case 's':
227 err = cn_printf(cn, "%ld", cprm->siginfo->si_signo);
228 break;
229 /* UNIX time of coredump */
230 case 't': {
231 struct timeval tv;
232 do_gettimeofday(&tv);
233 err = cn_printf(cn, "%lu", tv.tv_sec);
234 break;
236 /* hostname */
237 case 'h':
238 down_read(&uts_sem);
239 err = cn_esc_printf(cn, "%s",
240 utsname()->nodename);
241 up_read(&uts_sem);
242 break;
243 /* executable */
244 case 'e':
245 err = cn_esc_printf(cn, "%s", current->comm);
246 break;
247 case 'E':
248 err = cn_print_exe_file(cn);
249 break;
250 /* core limit size */
251 case 'c':
252 err = cn_printf(cn, "%lu",
253 rlimit(RLIMIT_CORE));
254 break;
255 default:
256 break;
258 ++pat_ptr;
261 if (err)
262 return err;
265 out:
266 /* Backward compatibility with core_uses_pid:
268 * If core_pattern does not include a %p (as is the default)
269 * and core_uses_pid is set, then .%pid will be appended to
270 * the filename. Do not do this for piped commands. */
271 if (!ispipe && !pid_in_pattern && core_uses_pid) {
272 err = cn_printf(cn, ".%d", task_tgid_vnr(current));
273 if (err)
274 return err;
276 return ispipe;
279 static int zap_process(struct task_struct *start, int exit_code)
281 struct task_struct *t;
282 int nr = 0;
284 start->signal->group_exit_code = exit_code;
285 start->signal->group_stop_count = 0;
287 t = start;
288 do {
289 task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
290 if (t != current && t->mm) {
291 sigaddset(&t->pending.signal, SIGKILL);
292 signal_wake_up(t, 1);
293 nr++;
295 } while_each_thread(start, t);
297 return nr;
300 static int zap_threads(struct task_struct *tsk, struct mm_struct *mm,
301 struct core_state *core_state, int exit_code)
303 struct task_struct *g, *p;
304 unsigned long flags;
305 int nr = -EAGAIN;
307 spin_lock_irq(&tsk->sighand->siglock);
308 if (!signal_group_exit(tsk->signal)) {
309 mm->core_state = core_state;
310 nr = zap_process(tsk, exit_code);
311 tsk->signal->group_exit_task = tsk;
312 /* ignore all signals except SIGKILL, see prepare_signal() */
313 tsk->signal->flags = SIGNAL_GROUP_COREDUMP;
314 clear_tsk_thread_flag(tsk, TIF_SIGPENDING);
316 spin_unlock_irq(&tsk->sighand->siglock);
317 if (unlikely(nr < 0))
318 return nr;
320 tsk->flags |= PF_DUMPCORE;
321 if (atomic_read(&mm->mm_users) == nr + 1)
322 goto done;
324 * We should find and kill all tasks which use this mm, and we should
325 * count them correctly into ->nr_threads. We don't take tasklist
326 * lock, but this is safe wrt:
328 * fork:
329 * None of sub-threads can fork after zap_process(leader). All
330 * processes which were created before this point should be
331 * visible to zap_threads() because copy_process() adds the new
332 * process to the tail of init_task.tasks list, and lock/unlock
333 * of ->siglock provides a memory barrier.
335 * do_exit:
336 * The caller holds mm->mmap_sem. This means that the task which
337 * uses this mm can't pass exit_mm(), so it can't exit or clear
338 * its ->mm.
340 * de_thread:
341 * It does list_replace_rcu(&leader->tasks, &current->tasks),
342 * we must see either old or new leader, this does not matter.
343 * However, it can change p->sighand, so lock_task_sighand(p)
344 * must be used. Since p->mm != NULL and we hold ->mmap_sem
345 * it can't fail.
347 * Note also that "g" can be the old leader with ->mm == NULL
348 * and already unhashed and thus removed from ->thread_group.
349 * This is OK, __unhash_process()->list_del_rcu() does not
350 * clear the ->next pointer, we will find the new leader via
351 * next_thread().
353 rcu_read_lock();
354 for_each_process(g) {
355 if (g == tsk->group_leader)
356 continue;
357 if (g->flags & PF_KTHREAD)
358 continue;
359 p = g;
360 do {
361 if (p->mm) {
362 if (unlikely(p->mm == mm)) {
363 lock_task_sighand(p, &flags);
364 nr += zap_process(p, exit_code);
365 p->signal->flags = SIGNAL_GROUP_EXIT;
366 unlock_task_sighand(p, &flags);
368 break;
370 } while_each_thread(g, p);
372 rcu_read_unlock();
373 done:
374 atomic_set(&core_state->nr_threads, nr);
375 return nr;
378 static int coredump_wait(int exit_code, struct core_state *core_state)
380 struct task_struct *tsk = current;
381 struct mm_struct *mm = tsk->mm;
382 int core_waiters = -EBUSY;
384 init_completion(&core_state->startup);
385 core_state->dumper.task = tsk;
386 core_state->dumper.next = NULL;
388 down_write(&mm->mmap_sem);
389 if (!mm->core_state)
390 core_waiters = zap_threads(tsk, mm, core_state, exit_code);
391 up_write(&mm->mmap_sem);
393 if (core_waiters > 0) {
394 struct core_thread *ptr;
396 wait_for_completion(&core_state->startup);
398 * Wait for all the threads to become inactive, so that
399 * all the thread context (extended register state, like
400 * fpu etc) gets copied to the memory.
402 ptr = core_state->dumper.next;
403 while (ptr != NULL) {
404 wait_task_inactive(ptr->task, 0);
405 ptr = ptr->next;
409 return core_waiters;
412 static void coredump_finish(struct mm_struct *mm, bool core_dumped)
414 struct core_thread *curr, *next;
415 struct task_struct *task;
417 spin_lock_irq(&current->sighand->siglock);
418 if (core_dumped && !__fatal_signal_pending(current))
419 current->signal->group_exit_code |= 0x80;
420 current->signal->group_exit_task = NULL;
421 current->signal->flags = SIGNAL_GROUP_EXIT;
422 spin_unlock_irq(&current->sighand->siglock);
424 next = mm->core_state->dumper.next;
425 while ((curr = next) != NULL) {
426 next = curr->next;
427 task = curr->task;
429 * see exit_mm(), curr->task must not see
430 * ->task == NULL before we read ->next.
432 smp_mb();
433 curr->task = NULL;
434 wake_up_process(task);
437 mm->core_state = NULL;
440 static bool dump_interrupted(void)
443 * SIGKILL or freezing() interrupt the coredumping. Perhaps we
444 * can do try_to_freeze() and check __fatal_signal_pending(),
445 * but then we need to teach dump_write() to restart and clear
446 * TIF_SIGPENDING.
448 return signal_pending(current);
451 static void wait_for_dump_helpers(struct file *file)
453 struct pipe_inode_info *pipe = file->private_data;
455 pipe_lock(pipe);
456 pipe->readers++;
457 pipe->writers--;
458 wake_up_interruptible_sync(&pipe->wait);
459 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
460 pipe_unlock(pipe);
463 * We actually want wait_event_freezable() but then we need
464 * to clear TIF_SIGPENDING and improve dump_interrupted().
466 wait_event_interruptible(pipe->wait, pipe->readers == 1);
468 pipe_lock(pipe);
469 pipe->readers--;
470 pipe->writers++;
471 pipe_unlock(pipe);
475 * umh_pipe_setup
476 * helper function to customize the process used
477 * to collect the core in userspace. Specifically
478 * it sets up a pipe and installs it as fd 0 (stdin)
479 * for the process. Returns 0 on success, or
480 * PTR_ERR on failure.
481 * Note that it also sets the core limit to 1. This
482 * is a special value that we use to trap recursive
483 * core dumps
485 static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
487 struct file *files[2];
488 struct coredump_params *cp = (struct coredump_params *)info->data;
489 int err = create_pipe_files(files, 0);
490 if (err)
491 return err;
493 cp->file = files[1];
495 err = replace_fd(0, files[0], 0);
496 fput(files[0]);
497 /* and disallow core files too */
498 current->signal->rlim[RLIMIT_CORE] = (struct rlimit){1, 1};
500 return err;
503 void do_coredump(const siginfo_t *siginfo)
505 struct core_state core_state;
506 struct core_name cn;
507 struct mm_struct *mm = current->mm;
508 struct linux_binfmt * binfmt;
509 const struct cred *old_cred;
510 struct cred *cred;
511 int retval = 0;
512 int ispipe;
513 struct files_struct *displaced;
514 /* require nonrelative corefile path and be extra careful */
515 bool need_suid_safe = false;
516 bool core_dumped = false;
517 static atomic_t core_dump_count = ATOMIC_INIT(0);
518 struct coredump_params cprm = {
519 .siginfo = siginfo,
520 .regs = signal_pt_regs(),
521 .limit = rlimit(RLIMIT_CORE),
523 * We must use the same mm->flags while dumping core to avoid
524 * inconsistency of bit flags, since this flag is not protected
525 * by any locks.
527 .mm_flags = mm->flags,
530 audit_core_dumps(siginfo->si_signo);
532 binfmt = mm->binfmt;
533 if (!binfmt || !binfmt->core_dump)
534 goto fail;
535 if (!__get_dumpable(cprm.mm_flags))
536 goto fail;
538 cred = prepare_creds();
539 if (!cred)
540 goto fail;
542 * We cannot trust fsuid as being the "true" uid of the process
543 * nor do we know its entire history. We only know it was tainted
544 * so we dump it as root in mode 2, and only into a controlled
545 * environment (pipe handler or fully qualified path).
547 if (__get_dumpable(cprm.mm_flags) == SUID_DUMP_ROOT) {
548 /* Setuid core dump mode */
549 cred->fsuid = GLOBAL_ROOT_UID; /* Dump root private */
550 need_suid_safe = true;
553 retval = coredump_wait(siginfo->si_signo, &core_state);
554 if (retval < 0)
555 goto fail_creds;
557 old_cred = override_creds(cred);
559 ispipe = format_corename(&cn, &cprm);
561 if (ispipe) {
562 int dump_count;
563 char **helper_argv;
564 struct subprocess_info *sub_info;
566 if (ispipe < 0) {
567 printk(KERN_WARNING "format_corename failed\n");
568 printk(KERN_WARNING "Aborting core\n");
569 goto fail_unlock;
572 if (cprm.limit == 1) {
573 /* See umh_pipe_setup() which sets RLIMIT_CORE = 1.
575 * Normally core limits are irrelevant to pipes, since
576 * we're not writing to the file system, but we use
577 * cprm.limit of 1 here as a speacial value, this is a
578 * consistent way to catch recursive crashes.
579 * We can still crash if the core_pattern binary sets
580 * RLIM_CORE = !1, but it runs as root, and can do
581 * lots of stupid things.
583 * Note that we use task_tgid_vnr here to grab the pid
584 * of the process group leader. That way we get the
585 * right pid if a thread in a multi-threaded
586 * core_pattern process dies.
588 printk(KERN_WARNING
589 "Process %d(%s) has RLIMIT_CORE set to 1\n",
590 task_tgid_vnr(current), current->comm);
591 printk(KERN_WARNING "Aborting core\n");
592 goto fail_unlock;
594 cprm.limit = RLIM_INFINITY;
596 dump_count = atomic_inc_return(&core_dump_count);
597 if (core_pipe_limit && (core_pipe_limit < dump_count)) {
598 printk(KERN_WARNING "Pid %d(%s) over core_pipe_limit\n",
599 task_tgid_vnr(current), current->comm);
600 printk(KERN_WARNING "Skipping core dump\n");
601 goto fail_dropcount;
604 helper_argv = argv_split(GFP_KERNEL, cn.corename, NULL);
605 if (!helper_argv) {
606 printk(KERN_WARNING "%s failed to allocate memory\n",
607 __func__);
608 goto fail_dropcount;
611 retval = -ENOMEM;
612 sub_info = call_usermodehelper_setup(helper_argv[0],
613 helper_argv, NULL, GFP_KERNEL,
614 umh_pipe_setup, NULL, &cprm);
615 if (sub_info)
616 retval = call_usermodehelper_exec(sub_info,
617 UMH_WAIT_EXEC);
619 argv_free(helper_argv);
620 if (retval) {
621 printk(KERN_INFO "Core dump to |%s pipe failed\n",
622 cn.corename);
623 goto close_fail;
625 } else {
626 struct inode *inode;
627 int open_flags = O_CREAT | O_RDWR | O_NOFOLLOW |
628 O_LARGEFILE | O_EXCL;
630 if (cprm.limit < binfmt->min_coredump)
631 goto fail_unlock;
633 if (need_suid_safe && cn.corename[0] != '/') {
634 printk(KERN_WARNING "Pid %d(%s) can only dump core "\
635 "to fully qualified path!\n",
636 task_tgid_vnr(current), current->comm);
637 printk(KERN_WARNING "Skipping core dump\n");
638 goto fail_unlock;
642 * Unlink the file if it exists unless this is a SUID
643 * binary - in that case, we're running around with root
644 * privs and don't want to unlink another user's coredump.
646 if (!need_suid_safe) {
647 mm_segment_t old_fs;
649 old_fs = get_fs();
650 set_fs(KERNEL_DS);
652 * If it doesn't exist, that's fine. If there's some
653 * other problem, we'll catch it at the filp_open().
655 (void) sys_unlink((const char __user *)cn.corename);
656 set_fs(old_fs);
660 * There is a race between unlinking and creating the
661 * file, but if that causes an EEXIST here, that's
662 * fine - another process raced with us while creating
663 * the corefile, and the other process won. To userspace,
664 * what matters is that at least one of the two processes
665 * writes its coredump successfully, not which one.
667 if (need_suid_safe) {
669 * Using user namespaces, normal user tasks can change
670 * their current->fs->root to point to arbitrary
671 * directories. Since the intention of the "only dump
672 * with a fully qualified path" rule is to control where
673 * coredumps may be placed using root privileges,
674 * current->fs->root must not be used. Instead, use the
675 * root directory of init_task.
677 struct path root;
679 task_lock(&init_task);
680 get_fs_root(init_task.fs, &root);
681 task_unlock(&init_task);
682 cprm.file = file_open_root(root.dentry, root.mnt,
683 cn.corename, open_flags, 0600);
684 path_put(&root);
685 } else {
686 cprm.file = filp_open(cn.corename, open_flags, 0600);
688 if (IS_ERR(cprm.file))
689 goto fail_unlock;
691 inode = file_inode(cprm.file);
692 if (inode->i_nlink > 1)
693 goto close_fail;
694 if (d_unhashed(cprm.file->f_path.dentry))
695 goto close_fail;
697 * AK: actually i see no reason to not allow this for named
698 * pipes etc, but keep the previous behaviour for now.
700 if (!S_ISREG(inode->i_mode))
701 goto close_fail;
703 * Dont allow local users get cute and trick others to coredump
704 * into their pre-created files.
706 if (!uid_eq(inode->i_uid, current_fsuid()))
707 goto close_fail;
708 if (!(cprm.file->f_mode & FMODE_CAN_WRITE))
709 goto close_fail;
710 if (do_truncate(cprm.file->f_path.dentry, 0, 0, cprm.file))
711 goto close_fail;
714 /* get us an unshared descriptor table; almost always a no-op */
715 retval = unshare_files(&displaced);
716 if (retval)
717 goto close_fail;
718 if (displaced)
719 put_files_struct(displaced);
720 if (!dump_interrupted()) {
721 file_start_write(cprm.file);
722 core_dumped = binfmt->core_dump(&cprm);
723 file_end_write(cprm.file);
725 if (ispipe && core_pipe_limit)
726 wait_for_dump_helpers(cprm.file);
727 close_fail:
728 if (cprm.file)
729 filp_close(cprm.file, NULL);
730 fail_dropcount:
731 if (ispipe)
732 atomic_dec(&core_dump_count);
733 fail_unlock:
734 kfree(cn.corename);
735 coredump_finish(mm, core_dumped);
736 revert_creds(old_cred);
737 fail_creds:
738 put_cred(cred);
739 fail:
740 return;
744 * Core dumping helper functions. These are the only things you should
745 * do on a core-file: use only these functions to write out all the
746 * necessary info.
748 int dump_emit(struct coredump_params *cprm, const void *addr, int nr)
750 struct file *file = cprm->file;
751 loff_t pos = file->f_pos;
752 ssize_t n;
753 if (cprm->written + nr > cprm->limit)
754 return 0;
755 while (nr) {
756 if (dump_interrupted())
757 return 0;
758 n = __kernel_write(file, addr, nr, &pos);
759 if (n <= 0)
760 return 0;
761 file->f_pos = pos;
762 cprm->written += n;
763 nr -= n;
765 return 1;
767 EXPORT_SYMBOL(dump_emit);
769 int dump_skip(struct coredump_params *cprm, size_t nr)
771 static char zeroes[PAGE_SIZE];
772 struct file *file = cprm->file;
773 if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
774 if (cprm->written + nr > cprm->limit)
775 return 0;
776 if (dump_interrupted() ||
777 file->f_op->llseek(file, nr, SEEK_CUR) < 0)
778 return 0;
779 cprm->written += nr;
780 return 1;
781 } else {
782 while (nr > PAGE_SIZE) {
783 if (!dump_emit(cprm, zeroes, PAGE_SIZE))
784 return 0;
785 nr -= PAGE_SIZE;
787 return dump_emit(cprm, zeroes, nr);
790 EXPORT_SYMBOL(dump_skip);
792 int dump_align(struct coredump_params *cprm, int align)
794 unsigned mod = cprm->written & (align - 1);
795 if (align & (align - 1))
796 return 0;
797 return mod ? dump_skip(cprm, align - mod) : 1;
799 EXPORT_SYMBOL(dump_align);