• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/proc/base.c
4  *
5  *  Copyright (C) 1991, 1992 Linus Torvalds
6  *
7  *  proc base directory handling functions
8  *
9  *  1999, Al Viro. Rewritten. Now it covers the whole per-process part.
10  *  Instead of using magical inumbers to determine the kind of object
11  *  we allocate and fill in-core inodes upon lookup. They don't even
12  *  go into icache. We cache the reference to task_struct upon lookup too.
13  *  Eventually it should become a filesystem in its own. We don't use the
14  *  rest of procfs anymore.
15  *
16  *
17  *  Changelog:
18  *  17-Jan-2005
19  *  Allan Bezerra
20  *  Bruna Moreira <bruna.moreira@indt.org.br>
21  *  Edjard Mota <edjard.mota@indt.org.br>
22  *  Ilias Biris <ilias.biris@indt.org.br>
23  *  Mauricio Lin <mauricio.lin@indt.org.br>
24  *
25  *  Embedded Linux Lab - 10LE Instituto Nokia de Tecnologia - INdT
26  *
27  *  A new process specific entry (smaps) included in /proc. It shows the
28  *  size of rss for each memory area. The maps entry lacks information
29  *  about physical memory size (rss) for each mapped file, i.e.,
30  *  rss information for executables and library files.
31  *  This additional information is useful for any tools that need to know
32  *  about physical memory consumption for a process specific library.
33  *
34  *  Changelog:
35  *  21-Feb-2005
36  *  Embedded Linux Lab - 10LE Instituto Nokia de Tecnologia - INdT
37  *  Pud inclusion in the page table walking.
38  *
39  *  ChangeLog:
40  *  10-Mar-2005
41  *  10LE Instituto Nokia de Tecnologia - INdT:
42  *  A better way to walks through the page table as suggested by Hugh Dickins.
43  *
44  *  Simo Piiroinen <simo.piiroinen@nokia.com>:
45  *  Smaps information related to shared, private, clean and dirty pages.
46  *
47  *  Paul Mundt <paul.mundt@nokia.com>:
48  *  Overall revision about smaps.
49  */
50 
51 #include <linux/uaccess.h>
52 
53 #include <linux/errno.h>
54 #include <linux/time.h>
55 #include <linux/proc_fs.h>
56 #include <linux/stat.h>
57 #include <linux/task_io_accounting_ops.h>
58 #include <linux/init.h>
59 #include <linux/capability.h>
60 #include <linux/file.h>
61 #include <linux/fdtable.h>
62 #include <linux/generic-radix-tree.h>
63 #include <linux/string.h>
64 #include <linux/seq_file.h>
65 #include <linux/namei.h>
66 #include <linux/mnt_namespace.h>
67 #include <linux/mm.h>
68 #include <linux/swap.h>
69 #include <linux/rcupdate.h>
70 #include <linux/kallsyms.h>
71 #include <linux/stacktrace.h>
72 #include <linux/resource.h>
73 #include <linux/module.h>
74 #include <linux/mount.h>
75 #include <linux/security.h>
76 #include <linux/ptrace.h>
77 #include <linux/tracehook.h>
78 #include <linux/printk.h>
79 #include <linux/cache.h>
80 #include <linux/cgroup.h>
81 #include <linux/cpuset.h>
82 #include <linux/audit.h>
83 #include <linux/poll.h>
84 #include <linux/nsproxy.h>
85 #include <linux/oom.h>
86 #include <linux/elf.h>
87 #include <linux/pid_namespace.h>
88 #include <linux/user_namespace.h>
89 #include <linux/fs_struct.h>
90 #include <linux/slab.h>
91 #include <linux/sched/autogroup.h>
92 #include <linux/sched/mm.h>
93 #include <linux/sched/coredump.h>
94 #include <linux/sched/debug.h>
95 #include <linux/sched/stat.h>
96 #include <linux/posix-timers.h>
97 #include <linux/time_namespace.h>
98 #include <linux/resctrl.h>
99 #include <linux/cpufreq_times.h>
100 #include <trace/events/oom.h>
101 #include "internal.h"
102 #include "fd.h"
103 
104 #include "../../lib/kstrtox.h"
105 
106 /* NOTE:
107  *	Implementing inode permission operations in /proc is almost
108  *	certainly an error.  Permission checks need to happen during
109  *	each system call not at open time.  The reason is that most of
110  *	what we wish to check for permissions in /proc varies at runtime.
111  *
112  *	The classic example of a problem is opening file descriptors
113  *	in /proc for a task before it execs a suid executable.
114  */
115 
116 static u8 nlink_tid __ro_after_init;
117 static u8 nlink_tgid __ro_after_init;
118 
119 struct pid_entry {
120 	const char *name;
121 	unsigned int len;
122 	umode_t mode;
123 	const struct inode_operations *iop;
124 	const struct file_operations *fop;
125 	union proc_op op;
126 };
127 
128 #define NOD(NAME, MODE, IOP, FOP, OP) {			\
129 	.name = (NAME),					\
130 	.len  = sizeof(NAME) - 1,			\
131 	.mode = MODE,					\
132 	.iop  = IOP,					\
133 	.fop  = FOP,					\
134 	.op   = OP,					\
135 }
136 
137 #define DIR(NAME, MODE, iops, fops)	\
138 	NOD(NAME, (S_IFDIR|(MODE)), &iops, &fops, {} )
139 #define LNK(NAME, get_link)					\
140 	NOD(NAME, (S_IFLNK|S_IRWXUGO),				\
141 		&proc_pid_link_inode_operations, NULL,		\
142 		{ .proc_get_link = get_link } )
143 #define REG(NAME, MODE, fops)				\
144 	NOD(NAME, (S_IFREG|(MODE)), NULL, &fops, {})
145 #define ONE(NAME, MODE, show)				\
146 	NOD(NAME, (S_IFREG|(MODE)),			\
147 		NULL, &proc_single_file_operations,	\
148 		{ .proc_show = show } )
149 #define ATTR(LSM, NAME, MODE)				\
150 	NOD(NAME, (S_IFREG|(MODE)),			\
151 		NULL, &proc_pid_attr_operations,	\
152 		{ .lsm = LSM })
153 
154 /*
155  * Count the number of hardlinks for the pid_entry table, excluding the .
156  * and .. links.
157  */
pid_entry_nlink(const struct pid_entry * entries,unsigned int n)158 static unsigned int __init pid_entry_nlink(const struct pid_entry *entries,
159 	unsigned int n)
160 {
161 	unsigned int i;
162 	unsigned int count;
163 
164 	count = 2;
165 	for (i = 0; i < n; ++i) {
166 		if (S_ISDIR(entries[i].mode))
167 			++count;
168 	}
169 
170 	return count;
171 }
172 
get_task_root(struct task_struct * task,struct path * root)173 static int get_task_root(struct task_struct *task, struct path *root)
174 {
175 	int result = -ENOENT;
176 
177 	task_lock(task);
178 	if (task->fs) {
179 		get_fs_root(task->fs, root);
180 		result = 0;
181 	}
182 	task_unlock(task);
183 	return result;
184 }
185 
proc_cwd_link(struct dentry * dentry,struct path * path)186 static int proc_cwd_link(struct dentry *dentry, struct path *path)
187 {
188 	struct task_struct *task = get_proc_task(d_inode(dentry));
189 	int result = -ENOENT;
190 
191 	if (task) {
192 		task_lock(task);
193 		if (task->fs) {
194 			get_fs_pwd(task->fs, path);
195 			result = 0;
196 		}
197 		task_unlock(task);
198 		put_task_struct(task);
199 	}
200 	return result;
201 }
202 
proc_root_link(struct dentry * dentry,struct path * path)203 static int proc_root_link(struct dentry *dentry, struct path *path)
204 {
205 	struct task_struct *task = get_proc_task(d_inode(dentry));
206 	int result = -ENOENT;
207 
208 	if (task) {
209 		result = get_task_root(task, path);
210 		put_task_struct(task);
211 	}
212 	return result;
213 }
214 
215 /*
216  * If the user used setproctitle(), we just get the string from
217  * user space at arg_start, and limit it to a maximum of one page.
218  */
get_mm_proctitle(struct mm_struct * mm,char __user * buf,size_t count,unsigned long pos,unsigned long arg_start)219 static ssize_t get_mm_proctitle(struct mm_struct *mm, char __user *buf,
220 				size_t count, unsigned long pos,
221 				unsigned long arg_start)
222 {
223 	char *page;
224 	int ret, got;
225 
226 	if (pos >= PAGE_SIZE)
227 		return 0;
228 
229 	page = (char *)__get_free_page(GFP_KERNEL);
230 	if (!page)
231 		return -ENOMEM;
232 
233 	ret = 0;
234 	got = access_remote_vm(mm, arg_start, page, PAGE_SIZE, FOLL_ANON);
235 	if (got > 0) {
236 		int len = strnlen(page, got);
237 
238 		/* Include the NUL character if it was found */
239 		if (len < got)
240 			len++;
241 
242 		if (len > pos) {
243 			len -= pos;
244 			if (len > count)
245 				len = count;
246 			len -= copy_to_user(buf, page+pos, len);
247 			if (!len)
248 				len = -EFAULT;
249 			ret = len;
250 		}
251 	}
252 	free_page((unsigned long)page);
253 	return ret;
254 }
255 
get_mm_cmdline(struct mm_struct * mm,char __user * buf,size_t count,loff_t * ppos)256 static ssize_t get_mm_cmdline(struct mm_struct *mm, char __user *buf,
257 			      size_t count, loff_t *ppos)
258 {
259 	unsigned long arg_start, arg_end, env_start, env_end;
260 	unsigned long pos, len;
261 	char *page, c;
262 
263 	/* Check if process spawned far enough to have cmdline. */
264 	if (!mm->env_end)
265 		return 0;
266 
267 	spin_lock(&mm->arg_lock);
268 	arg_start = mm->arg_start;
269 	arg_end = mm->arg_end;
270 	env_start = mm->env_start;
271 	env_end = mm->env_end;
272 	spin_unlock(&mm->arg_lock);
273 
274 	if (arg_start >= arg_end)
275 		return 0;
276 
277 	/*
278 	 * We allow setproctitle() to overwrite the argument
279 	 * strings, and overflow past the original end. But
280 	 * only when it overflows into the environment area.
281 	 */
282 	if (env_start != arg_end || env_end < env_start)
283 		env_start = env_end = arg_end;
284 	len = env_end - arg_start;
285 
286 	/* We're not going to care if "*ppos" has high bits set */
287 	pos = *ppos;
288 	if (pos >= len)
289 		return 0;
290 	if (count > len - pos)
291 		count = len - pos;
292 	if (!count)
293 		return 0;
294 
295 	/*
296 	 * Magical special case: if the argv[] end byte is not
297 	 * zero, the user has overwritten it with setproctitle(3).
298 	 *
299 	 * Possible future enhancement: do this only once when
300 	 * pos is 0, and set a flag in the 'struct file'.
301 	 */
302 	if (access_remote_vm(mm, arg_end-1, &c, 1, FOLL_ANON) == 1 && c)
303 		return get_mm_proctitle(mm, buf, count, pos, arg_start);
304 
305 	/*
306 	 * For the non-setproctitle() case we limit things strictly
307 	 * to the [arg_start, arg_end[ range.
308 	 */
309 	pos += arg_start;
310 	if (pos < arg_start || pos >= arg_end)
311 		return 0;
312 	if (count > arg_end - pos)
313 		count = arg_end - pos;
314 
315 	page = (char *)__get_free_page(GFP_KERNEL);
316 	if (!page)
317 		return -ENOMEM;
318 
319 	len = 0;
320 	while (count) {
321 		int got;
322 		size_t size = min_t(size_t, PAGE_SIZE, count);
323 
324 		got = access_remote_vm(mm, pos, page, size, FOLL_ANON);
325 		if (got <= 0)
326 			break;
327 		got -= copy_to_user(buf, page, got);
328 		if (unlikely(!got)) {
329 			if (!len)
330 				len = -EFAULT;
331 			break;
332 		}
333 		pos += got;
334 		buf += got;
335 		len += got;
336 		count -= got;
337 	}
338 
339 	free_page((unsigned long)page);
340 	return len;
341 }
342 
get_task_cmdline(struct task_struct * tsk,char __user * buf,size_t count,loff_t * pos)343 static ssize_t get_task_cmdline(struct task_struct *tsk, char __user *buf,
344 				size_t count, loff_t *pos)
345 {
346 	struct mm_struct *mm;
347 	ssize_t ret;
348 
349 	mm = get_task_mm(tsk);
350 	if (!mm)
351 		return 0;
352 
353 	ret = get_mm_cmdline(mm, buf, count, pos);
354 	mmput(mm);
355 	return ret;
356 }
357 
proc_pid_cmdline_read(struct file * file,char __user * buf,size_t count,loff_t * pos)358 static ssize_t proc_pid_cmdline_read(struct file *file, char __user *buf,
359 				     size_t count, loff_t *pos)
360 {
361 	struct task_struct *tsk;
362 	ssize_t ret;
363 
364 	BUG_ON(*pos < 0);
365 
366 	tsk = get_proc_task(file_inode(file));
367 	if (!tsk)
368 		return -ESRCH;
369 	ret = get_task_cmdline(tsk, buf, count, pos);
370 	put_task_struct(tsk);
371 	if (ret > 0)
372 		*pos += ret;
373 	return ret;
374 }
375 
376 static const struct file_operations proc_pid_cmdline_ops = {
377 	.read	= proc_pid_cmdline_read,
378 	.llseek	= generic_file_llseek,
379 };
380 
381 #ifdef CONFIG_KALLSYMS
382 /*
383  * Provides a wchan file via kallsyms in a proper one-value-per-file format.
384  * Returns the resolved symbol.  If that fails, simply return the address.
385  */
proc_pid_wchan(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)386 static int proc_pid_wchan(struct seq_file *m, struct pid_namespace *ns,
387 			  struct pid *pid, struct task_struct *task)
388 {
389 	unsigned long wchan;
390 	char symname[KSYM_NAME_LEN];
391 
392 	if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
393 		goto print0;
394 
395 	wchan = get_wchan(task);
396 	if (wchan && !lookup_symbol_name(wchan, symname)) {
397 		seq_puts(m, symname);
398 		return 0;
399 	}
400 
401 print0:
402 	seq_putc(m, '0');
403 	return 0;
404 }
405 #endif /* CONFIG_KALLSYMS */
406 
lock_trace(struct task_struct * task)407 static int lock_trace(struct task_struct *task)
408 {
409 	int err = down_read_killable(&task->signal->exec_update_lock);
410 	if (err)
411 		return err;
412 	if (!ptrace_may_access(task, PTRACE_MODE_ATTACH_FSCREDS)) {
413 		up_read(&task->signal->exec_update_lock);
414 		return -EPERM;
415 	}
416 	return 0;
417 }
418 
unlock_trace(struct task_struct * task)419 static void unlock_trace(struct task_struct *task)
420 {
421 	up_read(&task->signal->exec_update_lock);
422 }
423 
424 #ifdef CONFIG_STACKTRACE
425 
426 #define MAX_STACK_TRACE_DEPTH	64
427 
proc_pid_stack(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)428 static int proc_pid_stack(struct seq_file *m, struct pid_namespace *ns,
429 			  struct pid *pid, struct task_struct *task)
430 {
431 	unsigned long *entries;
432 	int err;
433 
434 	/*
435 	 * The ability to racily run the kernel stack unwinder on a running task
436 	 * and then observe the unwinder output is scary; while it is useful for
437 	 * debugging kernel issues, it can also allow an attacker to leak kernel
438 	 * stack contents.
439 	 * Doing this in a manner that is at least safe from races would require
440 	 * some work to ensure that the remote task can not be scheduled; and
441 	 * even then, this would still expose the unwinder as local attack
442 	 * surface.
443 	 * Therefore, this interface is restricted to root.
444 	 */
445 	if (!file_ns_capable(m->file, &init_user_ns, CAP_SYS_ADMIN))
446 		return -EACCES;
447 
448 	entries = kmalloc_array(MAX_STACK_TRACE_DEPTH, sizeof(*entries),
449 				GFP_KERNEL);
450 	if (!entries)
451 		return -ENOMEM;
452 
453 	err = lock_trace(task);
454 	if (!err) {
455 		unsigned int i, nr_entries;
456 
457 		nr_entries = stack_trace_save_tsk(task, entries,
458 						  MAX_STACK_TRACE_DEPTH, 0);
459 
460 		for (i = 0; i < nr_entries; i++) {
461 			seq_printf(m, "[<0>] %pB\n", (void *)entries[i]);
462 		}
463 
464 		unlock_trace(task);
465 	}
466 	kfree(entries);
467 
468 	return err;
469 }
470 #endif
471 
472 #ifdef CONFIG_SCHED_INFO
473 /*
474  * Provides /proc/PID/schedstat
475  */
proc_pid_schedstat(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)476 static int proc_pid_schedstat(struct seq_file *m, struct pid_namespace *ns,
477 			      struct pid *pid, struct task_struct *task)
478 {
479 	if (unlikely(!sched_info_on()))
480 		seq_puts(m, "0 0 0\n");
481 	else
482 		seq_printf(m, "%llu %llu %lu\n",
483 		   (unsigned long long)task->se.sum_exec_runtime,
484 		   (unsigned long long)task->sched_info.run_delay,
485 		   task->sched_info.pcount);
486 
487 	return 0;
488 }
489 #endif
490 
491 #ifdef CONFIG_LATENCYTOP
lstats_show_proc(struct seq_file * m,void * v)492 static int lstats_show_proc(struct seq_file *m, void *v)
493 {
494 	int i;
495 	struct inode *inode = m->private;
496 	struct task_struct *task = get_proc_task(inode);
497 
498 	if (!task)
499 		return -ESRCH;
500 	seq_puts(m, "Latency Top version : v0.1\n");
501 	for (i = 0; i < LT_SAVECOUNT; i++) {
502 		struct latency_record *lr = &task->latency_record[i];
503 		if (lr->backtrace[0]) {
504 			int q;
505 			seq_printf(m, "%i %li %li",
506 				   lr->count, lr->time, lr->max);
507 			for (q = 0; q < LT_BACKTRACEDEPTH; q++) {
508 				unsigned long bt = lr->backtrace[q];
509 
510 				if (!bt)
511 					break;
512 				seq_printf(m, " %ps", (void *)bt);
513 			}
514 			seq_putc(m, '\n');
515 		}
516 
517 	}
518 	put_task_struct(task);
519 	return 0;
520 }
521 
lstats_open(struct inode * inode,struct file * file)522 static int lstats_open(struct inode *inode, struct file *file)
523 {
524 	return single_open(file, lstats_show_proc, inode);
525 }
526 
lstats_write(struct file * file,const char __user * buf,size_t count,loff_t * offs)527 static ssize_t lstats_write(struct file *file, const char __user *buf,
528 			    size_t count, loff_t *offs)
529 {
530 	struct task_struct *task = get_proc_task(file_inode(file));
531 
532 	if (!task)
533 		return -ESRCH;
534 	clear_tsk_latency_tracing(task);
535 	put_task_struct(task);
536 
537 	return count;
538 }
539 
540 static const struct file_operations proc_lstats_operations = {
541 	.open		= lstats_open,
542 	.read		= seq_read,
543 	.write		= lstats_write,
544 	.llseek		= seq_lseek,
545 	.release	= single_release,
546 };
547 
548 #endif
549 
proc_oom_score(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)550 static int proc_oom_score(struct seq_file *m, struct pid_namespace *ns,
551 			  struct pid *pid, struct task_struct *task)
552 {
553 	unsigned long totalpages = totalram_pages() + total_swap_pages;
554 	unsigned long points = 0;
555 	long badness;
556 
557 	badness = oom_badness(task, totalpages);
558 	/*
559 	 * Special case OOM_SCORE_ADJ_MIN for all others scale the
560 	 * badness value into [0, 2000] range which we have been
561 	 * exporting for a long time so userspace might depend on it.
562 	 */
563 	if (badness != LONG_MIN)
564 		points = (1000 + badness * 1000 / (long)totalpages) * 2 / 3;
565 
566 	seq_printf(m, "%lu\n", points);
567 
568 	return 0;
569 }
570 
571 struct limit_names {
572 	const char *name;
573 	const char *unit;
574 };
575 
576 static const struct limit_names lnames[RLIM_NLIMITS] = {
577 	[RLIMIT_CPU] = {"Max cpu time", "seconds"},
578 	[RLIMIT_FSIZE] = {"Max file size", "bytes"},
579 	[RLIMIT_DATA] = {"Max data size", "bytes"},
580 	[RLIMIT_STACK] = {"Max stack size", "bytes"},
581 	[RLIMIT_CORE] = {"Max core file size", "bytes"},
582 	[RLIMIT_RSS] = {"Max resident set", "bytes"},
583 	[RLIMIT_NPROC] = {"Max processes", "processes"},
584 	[RLIMIT_NOFILE] = {"Max open files", "files"},
585 	[RLIMIT_MEMLOCK] = {"Max locked memory", "bytes"},
586 	[RLIMIT_AS] = {"Max address space", "bytes"},
587 	[RLIMIT_LOCKS] = {"Max file locks", "locks"},
588 	[RLIMIT_SIGPENDING] = {"Max pending signals", "signals"},
589 	[RLIMIT_MSGQUEUE] = {"Max msgqueue size", "bytes"},
590 	[RLIMIT_NICE] = {"Max nice priority", NULL},
591 	[RLIMIT_RTPRIO] = {"Max realtime priority", NULL},
592 	[RLIMIT_RTTIME] = {"Max realtime timeout", "us"},
593 };
594 
595 /* Display limits for a process */
proc_pid_limits(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)596 static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns,
597 			   struct pid *pid, struct task_struct *task)
598 {
599 	unsigned int i;
600 	unsigned long flags;
601 
602 	struct rlimit rlim[RLIM_NLIMITS];
603 
604 	if (!lock_task_sighand(task, &flags))
605 		return 0;
606 	memcpy(rlim, task->signal->rlim, sizeof(struct rlimit) * RLIM_NLIMITS);
607 	unlock_task_sighand(task, &flags);
608 
609 	/*
610 	 * print the file header
611 	 */
612 	seq_puts(m, "Limit                     "
613 		"Soft Limit           "
614 		"Hard Limit           "
615 		"Units     \n");
616 
617 	for (i = 0; i < RLIM_NLIMITS; i++) {
618 		if (rlim[i].rlim_cur == RLIM_INFINITY)
619 			seq_printf(m, "%-25s %-20s ",
620 				   lnames[i].name, "unlimited");
621 		else
622 			seq_printf(m, "%-25s %-20lu ",
623 				   lnames[i].name, rlim[i].rlim_cur);
624 
625 		if (rlim[i].rlim_max == RLIM_INFINITY)
626 			seq_printf(m, "%-20s ", "unlimited");
627 		else
628 			seq_printf(m, "%-20lu ", rlim[i].rlim_max);
629 
630 		if (lnames[i].unit)
631 			seq_printf(m, "%-10s\n", lnames[i].unit);
632 		else
633 			seq_putc(m, '\n');
634 	}
635 
636 	return 0;
637 }
638 
639 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
proc_pid_syscall(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)640 static int proc_pid_syscall(struct seq_file *m, struct pid_namespace *ns,
641 			    struct pid *pid, struct task_struct *task)
642 {
643 	struct syscall_info info;
644 	u64 *args = &info.data.args[0];
645 	int res;
646 
647 	res = lock_trace(task);
648 	if (res)
649 		return res;
650 
651 	if (task_current_syscall(task, &info))
652 		seq_puts(m, "running\n");
653 	else if (info.data.nr < 0)
654 		seq_printf(m, "%d 0x%llx 0x%llx\n",
655 			   info.data.nr, info.sp, info.data.instruction_pointer);
656 	else
657 		seq_printf(m,
658 		       "%d 0x%llx 0x%llx 0x%llx 0x%llx 0x%llx 0x%llx 0x%llx 0x%llx\n",
659 		       info.data.nr,
660 		       args[0], args[1], args[2], args[3], args[4], args[5],
661 		       info.sp, info.data.instruction_pointer);
662 	unlock_trace(task);
663 
664 	return 0;
665 }
666 #endif /* CONFIG_HAVE_ARCH_TRACEHOOK */
667 
668 /************************************************************************/
669 /*                       Here the fs part begins                        */
670 /************************************************************************/
671 
672 /* permission checks */
proc_fd_access_allowed(struct inode * inode)673 static int proc_fd_access_allowed(struct inode *inode)
674 {
675 	struct task_struct *task;
676 	int allowed = 0;
677 	/* Allow access to a task's file descriptors if it is us or we
678 	 * may use ptrace attach to the process and find out that
679 	 * information.
680 	 */
681 	task = get_proc_task(inode);
682 	if (task) {
683 		allowed = ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS);
684 		put_task_struct(task);
685 	}
686 	return allowed;
687 }
688 
proc_setattr(struct dentry * dentry,struct iattr * attr)689 int proc_setattr(struct dentry *dentry, struct iattr *attr)
690 {
691 	int error;
692 	struct inode *inode = d_inode(dentry);
693 
694 	if (attr->ia_valid & ATTR_MODE)
695 		return -EPERM;
696 
697 	error = setattr_prepare(dentry, attr);
698 	if (error)
699 		return error;
700 
701 	setattr_copy(inode, attr);
702 	mark_inode_dirty(inode);
703 	return 0;
704 }
705 
706 /*
707  * May current process learn task's sched/cmdline info (for hide_pid_min=1)
708  * or euid/egid (for hide_pid_min=2)?
709  */
has_pid_permissions(struct proc_fs_info * fs_info,struct task_struct * task,enum proc_hidepid hide_pid_min)710 static bool has_pid_permissions(struct proc_fs_info *fs_info,
711 				 struct task_struct *task,
712 				 enum proc_hidepid hide_pid_min)
713 {
714 	/*
715 	 * If 'hidpid' mount option is set force a ptrace check,
716 	 * we indicate that we are using a filesystem syscall
717 	 * by passing PTRACE_MODE_READ_FSCREDS
718 	 */
719 	if (fs_info->hide_pid == HIDEPID_NOT_PTRACEABLE)
720 		return ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS);
721 
722 	if (fs_info->hide_pid < hide_pid_min)
723 		return true;
724 	if (in_group_p(fs_info->pid_gid))
725 		return true;
726 	return ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS);
727 }
728 
729 
proc_pid_permission(struct inode * inode,int mask)730 static int proc_pid_permission(struct inode *inode, int mask)
731 {
732 	struct proc_fs_info *fs_info = proc_sb_info(inode->i_sb);
733 	struct task_struct *task;
734 	bool has_perms;
735 
736 	task = get_proc_task(inode);
737 	if (!task)
738 		return -ESRCH;
739 	has_perms = has_pid_permissions(fs_info, task, HIDEPID_NO_ACCESS);
740 	put_task_struct(task);
741 
742 	if (!has_perms) {
743 		if (fs_info->hide_pid == HIDEPID_INVISIBLE) {
744 			/*
745 			 * Let's make getdents(), stat(), and open()
746 			 * consistent with each other.  If a process
747 			 * may not stat() a file, it shouldn't be seen
748 			 * in procfs at all.
749 			 */
750 			return -ENOENT;
751 		}
752 
753 		return -EPERM;
754 	}
755 	return generic_permission(inode, mask);
756 }
757 
758 
759 
760 static const struct inode_operations proc_def_inode_operations = {
761 	.setattr	= proc_setattr,
762 };
763 
proc_single_show(struct seq_file * m,void * v)764 static int proc_single_show(struct seq_file *m, void *v)
765 {
766 	struct inode *inode = m->private;
767 	struct pid_namespace *ns = proc_pid_ns(inode->i_sb);
768 	struct pid *pid = proc_pid(inode);
769 	struct task_struct *task;
770 	int ret;
771 
772 	task = get_pid_task(pid, PIDTYPE_PID);
773 	if (!task)
774 		return -ESRCH;
775 
776 	ret = PROC_I(inode)->op.proc_show(m, ns, pid, task);
777 
778 	put_task_struct(task);
779 	return ret;
780 }
781 
proc_single_open(struct inode * inode,struct file * filp)782 static int proc_single_open(struct inode *inode, struct file *filp)
783 {
784 	return single_open(filp, proc_single_show, inode);
785 }
786 
787 static const struct file_operations proc_single_file_operations = {
788 	.open		= proc_single_open,
789 	.read		= seq_read,
790 	.llseek		= seq_lseek,
791 	.release	= single_release,
792 };
793 
794 
proc_mem_open(struct inode * inode,unsigned int mode)795 struct mm_struct *proc_mem_open(struct inode *inode, unsigned int mode)
796 {
797 	struct task_struct *task = get_proc_task(inode);
798 	struct mm_struct *mm = ERR_PTR(-ESRCH);
799 
800 	if (task) {
801 		mm = mm_access(task, mode | PTRACE_MODE_FSCREDS);
802 		put_task_struct(task);
803 
804 		if (!IS_ERR_OR_NULL(mm)) {
805 			/* ensure this mm_struct can't be freed */
806 			mmgrab(mm);
807 			/* but do not pin its memory */
808 			mmput(mm);
809 		}
810 	}
811 
812 	return mm;
813 }
814 
__mem_open(struct inode * inode,struct file * file,unsigned int mode)815 static int __mem_open(struct inode *inode, struct file *file, unsigned int mode)
816 {
817 	struct mm_struct *mm = proc_mem_open(inode, mode);
818 
819 	if (IS_ERR(mm))
820 		return PTR_ERR(mm);
821 
822 	file->private_data = mm;
823 	return 0;
824 }
825 
mem_open(struct inode * inode,struct file * file)826 static int mem_open(struct inode *inode, struct file *file)
827 {
828 	int ret = __mem_open(inode, file, PTRACE_MODE_ATTACH);
829 
830 	/* OK to pass negative loff_t, we can catch out-of-range */
831 	file->f_mode |= FMODE_UNSIGNED_OFFSET;
832 
833 	return ret;
834 }
835 
mem_rw(struct file * file,char __user * buf,size_t count,loff_t * ppos,int write)836 static ssize_t mem_rw(struct file *file, char __user *buf,
837 			size_t count, loff_t *ppos, int write)
838 {
839 	struct mm_struct *mm = file->private_data;
840 	unsigned long addr = *ppos;
841 	ssize_t copied;
842 	char *page;
843 	unsigned int flags;
844 
845 	if (!mm)
846 		return 0;
847 
848 	page = (char *)__get_free_page(GFP_KERNEL);
849 	if (!page)
850 		return -ENOMEM;
851 
852 	copied = 0;
853 	if (!mmget_not_zero(mm))
854 		goto free;
855 
856 	flags = FOLL_FORCE | (write ? FOLL_WRITE : 0);
857 
858 	while (count > 0) {
859 		size_t this_len = min_t(size_t, count, PAGE_SIZE);
860 
861 		if (write && copy_from_user(page, buf, this_len)) {
862 			copied = -EFAULT;
863 			break;
864 		}
865 
866 		this_len = access_remote_vm(mm, addr, page, this_len, flags);
867 		if (!this_len) {
868 			if (!copied)
869 				copied = -EIO;
870 			break;
871 		}
872 
873 		if (!write && copy_to_user(buf, page, this_len)) {
874 			copied = -EFAULT;
875 			break;
876 		}
877 
878 		buf += this_len;
879 		addr += this_len;
880 		copied += this_len;
881 		count -= this_len;
882 	}
883 	*ppos = addr;
884 
885 	mmput(mm);
886 free:
887 	free_page((unsigned long) page);
888 	return copied;
889 }
890 
mem_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)891 static ssize_t mem_read(struct file *file, char __user *buf,
892 			size_t count, loff_t *ppos)
893 {
894 	return mem_rw(file, buf, count, ppos, 0);
895 }
896 
mem_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)897 static ssize_t mem_write(struct file *file, const char __user *buf,
898 			 size_t count, loff_t *ppos)
899 {
900 	return mem_rw(file, (char __user*)buf, count, ppos, 1);
901 }
902 
mem_lseek(struct file * file,loff_t offset,int orig)903 loff_t mem_lseek(struct file *file, loff_t offset, int orig)
904 {
905 	switch (orig) {
906 	case 0:
907 		file->f_pos = offset;
908 		break;
909 	case 1:
910 		file->f_pos += offset;
911 		break;
912 	default:
913 		return -EINVAL;
914 	}
915 	force_successful_syscall_return();
916 	return file->f_pos;
917 }
918 
mem_release(struct inode * inode,struct file * file)919 static int mem_release(struct inode *inode, struct file *file)
920 {
921 	struct mm_struct *mm = file->private_data;
922 	if (mm)
923 		mmdrop(mm);
924 	return 0;
925 }
926 
927 static const struct file_operations proc_mem_operations = {
928 	.llseek		= mem_lseek,
929 	.read		= mem_read,
930 	.write		= mem_write,
931 	.open		= mem_open,
932 	.release	= mem_release,
933 };
934 
environ_open(struct inode * inode,struct file * file)935 static int environ_open(struct inode *inode, struct file *file)
936 {
937 	return __mem_open(inode, file, PTRACE_MODE_READ);
938 }
939 
environ_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)940 static ssize_t environ_read(struct file *file, char __user *buf,
941 			size_t count, loff_t *ppos)
942 {
943 	char *page;
944 	unsigned long src = *ppos;
945 	int ret = 0;
946 	struct mm_struct *mm = file->private_data;
947 	unsigned long env_start, env_end;
948 
949 	/* Ensure the process spawned far enough to have an environment. */
950 	if (!mm || !mm->env_end)
951 		return 0;
952 
953 	page = (char *)__get_free_page(GFP_KERNEL);
954 	if (!page)
955 		return -ENOMEM;
956 
957 	ret = 0;
958 	if (!mmget_not_zero(mm))
959 		goto free;
960 
961 	spin_lock(&mm->arg_lock);
962 	env_start = mm->env_start;
963 	env_end = mm->env_end;
964 	spin_unlock(&mm->arg_lock);
965 
966 	while (count > 0) {
967 		size_t this_len, max_len;
968 		int retval;
969 
970 		if (src >= (env_end - env_start))
971 			break;
972 
973 		this_len = env_end - (env_start + src);
974 
975 		max_len = min_t(size_t, PAGE_SIZE, count);
976 		this_len = min(max_len, this_len);
977 
978 		retval = access_remote_vm(mm, (env_start + src), page, this_len, FOLL_ANON);
979 
980 		if (retval <= 0) {
981 			ret = retval;
982 			break;
983 		}
984 
985 		if (copy_to_user(buf, page, retval)) {
986 			ret = -EFAULT;
987 			break;
988 		}
989 
990 		ret += retval;
991 		src += retval;
992 		buf += retval;
993 		count -= retval;
994 	}
995 	*ppos = src;
996 	mmput(mm);
997 
998 free:
999 	free_page((unsigned long) page);
1000 	return ret;
1001 }
1002 
1003 static const struct file_operations proc_environ_operations = {
1004 	.open		= environ_open,
1005 	.read		= environ_read,
1006 	.llseek		= generic_file_llseek,
1007 	.release	= mem_release,
1008 };
1009 
auxv_open(struct inode * inode,struct file * file)1010 static int auxv_open(struct inode *inode, struct file *file)
1011 {
1012 	return __mem_open(inode, file, PTRACE_MODE_READ_FSCREDS);
1013 }
1014 
auxv_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)1015 static ssize_t auxv_read(struct file *file, char __user *buf,
1016 			size_t count, loff_t *ppos)
1017 {
1018 	struct mm_struct *mm = file->private_data;
1019 	unsigned int nwords = 0;
1020 
1021 	if (!mm)
1022 		return 0;
1023 	do {
1024 		nwords += 2;
1025 	} while (mm->saved_auxv[nwords - 2] != 0); /* AT_NULL */
1026 	return simple_read_from_buffer(buf, count, ppos, mm->saved_auxv,
1027 				       nwords * sizeof(mm->saved_auxv[0]));
1028 }
1029 
1030 static const struct file_operations proc_auxv_operations = {
1031 	.open		= auxv_open,
1032 	.read		= auxv_read,
1033 	.llseek		= generic_file_llseek,
1034 	.release	= mem_release,
1035 };
1036 
oom_adj_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)1037 static ssize_t oom_adj_read(struct file *file, char __user *buf, size_t count,
1038 			    loff_t *ppos)
1039 {
1040 	struct task_struct *task = get_proc_task(file_inode(file));
1041 	char buffer[PROC_NUMBUF];
1042 	int oom_adj = OOM_ADJUST_MIN;
1043 	size_t len;
1044 
1045 	if (!task)
1046 		return -ESRCH;
1047 	if (task->signal->oom_score_adj == OOM_SCORE_ADJ_MAX)
1048 		oom_adj = OOM_ADJUST_MAX;
1049 	else
1050 		oom_adj = (task->signal->oom_score_adj * -OOM_DISABLE) /
1051 			  OOM_SCORE_ADJ_MAX;
1052 	put_task_struct(task);
1053 	if (oom_adj > OOM_ADJUST_MAX)
1054 		oom_adj = OOM_ADJUST_MAX;
1055 	len = snprintf(buffer, sizeof(buffer), "%d\n", oom_adj);
1056 	return simple_read_from_buffer(buf, count, ppos, buffer, len);
1057 }
1058 
__set_oom_adj(struct file * file,int oom_adj,bool legacy)1059 static int __set_oom_adj(struct file *file, int oom_adj, bool legacy)
1060 {
1061 	struct mm_struct *mm = NULL;
1062 	struct task_struct *task;
1063 	int err = 0;
1064 
1065 	task = get_proc_task(file_inode(file));
1066 	if (!task)
1067 		return -ESRCH;
1068 
1069 	mutex_lock(&oom_adj_mutex);
1070 	if (legacy) {
1071 		if (oom_adj < task->signal->oom_score_adj &&
1072 				!capable(CAP_SYS_RESOURCE)) {
1073 			err = -EACCES;
1074 			goto err_unlock;
1075 		}
1076 		/*
1077 		 * /proc/pid/oom_adj is provided for legacy purposes, ask users to use
1078 		 * /proc/pid/oom_score_adj instead.
1079 		 */
1080 		pr_warn_once("%s (%d): /proc/%d/oom_adj is deprecated, please use /proc/%d/oom_score_adj instead.\n",
1081 			  current->comm, task_pid_nr(current), task_pid_nr(task),
1082 			  task_pid_nr(task));
1083 	} else {
1084 		if ((short)oom_adj < task->signal->oom_score_adj_min &&
1085 				!capable(CAP_SYS_RESOURCE)) {
1086 			err = -EACCES;
1087 			goto err_unlock;
1088 		}
1089 	}
1090 
1091 	/*
1092 	 * Make sure we will check other processes sharing the mm if this is
1093 	 * not vfrok which wants its own oom_score_adj.
1094 	 * pin the mm so it doesn't go away and get reused after task_unlock
1095 	 */
1096 	if (!task->vfork_done) {
1097 		struct task_struct *p = find_lock_task_mm(task);
1098 
1099 		if (p) {
1100 			if (test_bit(MMF_MULTIPROCESS, &p->mm->flags)) {
1101 				mm = p->mm;
1102 				mmgrab(mm);
1103 			}
1104 			task_unlock(p);
1105 		}
1106 	}
1107 
1108 	task->signal->oom_score_adj = oom_adj;
1109 	if (!legacy && has_capability_noaudit(current, CAP_SYS_RESOURCE))
1110 		task->signal->oom_score_adj_min = (short)oom_adj;
1111 	trace_oom_score_adj_update(task);
1112 
1113 	if (mm) {
1114 		struct task_struct *p;
1115 
1116 		rcu_read_lock();
1117 		for_each_process(p) {
1118 			if (same_thread_group(task, p))
1119 				continue;
1120 
1121 			/* do not touch kernel threads or the global init */
1122 			if (p->flags & PF_KTHREAD || is_global_init(p))
1123 				continue;
1124 
1125 			task_lock(p);
1126 			if (!p->vfork_done && process_shares_mm(p, mm)) {
1127 				p->signal->oom_score_adj = oom_adj;
1128 				if (!legacy && has_capability_noaudit(current, CAP_SYS_RESOURCE))
1129 					p->signal->oom_score_adj_min = (short)oom_adj;
1130 			}
1131 			task_unlock(p);
1132 		}
1133 		rcu_read_unlock();
1134 		mmdrop(mm);
1135 	}
1136 err_unlock:
1137 	mutex_unlock(&oom_adj_mutex);
1138 	put_task_struct(task);
1139 	return err;
1140 }
1141 
1142 /*
1143  * /proc/pid/oom_adj exists solely for backwards compatibility with previous
1144  * kernels.  The effective policy is defined by oom_score_adj, which has a
1145  * different scale: oom_adj grew exponentially and oom_score_adj grows linearly.
1146  * Values written to oom_adj are simply mapped linearly to oom_score_adj.
1147  * Processes that become oom disabled via oom_adj will still be oom disabled
1148  * with this implementation.
1149  *
1150  * oom_adj cannot be removed since existing userspace binaries use it.
1151  */
oom_adj_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)1152 static ssize_t oom_adj_write(struct file *file, const char __user *buf,
1153 			     size_t count, loff_t *ppos)
1154 {
1155 	char buffer[PROC_NUMBUF];
1156 	int oom_adj;
1157 	int err;
1158 
1159 	memset(buffer, 0, sizeof(buffer));
1160 	if (count > sizeof(buffer) - 1)
1161 		count = sizeof(buffer) - 1;
1162 	if (copy_from_user(buffer, buf, count)) {
1163 		err = -EFAULT;
1164 		goto out;
1165 	}
1166 
1167 	err = kstrtoint(strstrip(buffer), 0, &oom_adj);
1168 	if (err)
1169 		goto out;
1170 	if ((oom_adj < OOM_ADJUST_MIN || oom_adj > OOM_ADJUST_MAX) &&
1171 	     oom_adj != OOM_DISABLE) {
1172 		err = -EINVAL;
1173 		goto out;
1174 	}
1175 
1176 	/*
1177 	 * Scale /proc/pid/oom_score_adj appropriately ensuring that a maximum
1178 	 * value is always attainable.
1179 	 */
1180 	if (oom_adj == OOM_ADJUST_MAX)
1181 		oom_adj = OOM_SCORE_ADJ_MAX;
1182 	else
1183 		oom_adj = (oom_adj * OOM_SCORE_ADJ_MAX) / -OOM_DISABLE;
1184 
1185 	err = __set_oom_adj(file, oom_adj, true);
1186 out:
1187 	return err < 0 ? err : count;
1188 }
1189 
1190 static const struct file_operations proc_oom_adj_operations = {
1191 	.read		= oom_adj_read,
1192 	.write		= oom_adj_write,
1193 	.llseek		= generic_file_llseek,
1194 };
1195 
oom_score_adj_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)1196 static ssize_t oom_score_adj_read(struct file *file, char __user *buf,
1197 					size_t count, loff_t *ppos)
1198 {
1199 	struct task_struct *task = get_proc_task(file_inode(file));
1200 	char buffer[PROC_NUMBUF];
1201 	short oom_score_adj = OOM_SCORE_ADJ_MIN;
1202 	size_t len;
1203 
1204 	if (!task)
1205 		return -ESRCH;
1206 	oom_score_adj = task->signal->oom_score_adj;
1207 	put_task_struct(task);
1208 	len = snprintf(buffer, sizeof(buffer), "%hd\n", oom_score_adj);
1209 	return simple_read_from_buffer(buf, count, ppos, buffer, len);
1210 }
1211 
oom_score_adj_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)1212 static ssize_t oom_score_adj_write(struct file *file, const char __user *buf,
1213 					size_t count, loff_t *ppos)
1214 {
1215 	char buffer[PROC_NUMBUF];
1216 	int oom_score_adj;
1217 	int err;
1218 
1219 	memset(buffer, 0, sizeof(buffer));
1220 	if (count > sizeof(buffer) - 1)
1221 		count = sizeof(buffer) - 1;
1222 	if (copy_from_user(buffer, buf, count)) {
1223 		err = -EFAULT;
1224 		goto out;
1225 	}
1226 
1227 	err = kstrtoint(strstrip(buffer), 0, &oom_score_adj);
1228 	if (err)
1229 		goto out;
1230 	if (oom_score_adj < OOM_SCORE_ADJ_MIN ||
1231 			oom_score_adj > OOM_SCORE_ADJ_MAX) {
1232 		err = -EINVAL;
1233 		goto out;
1234 	}
1235 
1236 	err = __set_oom_adj(file, oom_score_adj, false);
1237 out:
1238 	return err < 0 ? err : count;
1239 }
1240 
1241 static const struct file_operations proc_oom_score_adj_operations = {
1242 	.read		= oom_score_adj_read,
1243 	.write		= oom_score_adj_write,
1244 	.llseek		= default_llseek,
1245 };
1246 
1247 #ifdef CONFIG_AUDIT
1248 #define TMPBUFLEN 11
proc_loginuid_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)1249 static ssize_t proc_loginuid_read(struct file * file, char __user * buf,
1250 				  size_t count, loff_t *ppos)
1251 {
1252 	struct inode * inode = file_inode(file);
1253 	struct task_struct *task = get_proc_task(inode);
1254 	ssize_t length;
1255 	char tmpbuf[TMPBUFLEN];
1256 
1257 	if (!task)
1258 		return -ESRCH;
1259 	length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
1260 			   from_kuid(file->f_cred->user_ns,
1261 				     audit_get_loginuid(task)));
1262 	put_task_struct(task);
1263 	return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
1264 }
1265 
proc_loginuid_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)1266 static ssize_t proc_loginuid_write(struct file * file, const char __user * buf,
1267 				   size_t count, loff_t *ppos)
1268 {
1269 	struct inode * inode = file_inode(file);
1270 	uid_t loginuid;
1271 	kuid_t kloginuid;
1272 	int rv;
1273 
1274 	/* Don't let kthreads write their own loginuid */
1275 	if (current->flags & PF_KTHREAD)
1276 		return -EPERM;
1277 
1278 	rcu_read_lock();
1279 	if (current != pid_task(proc_pid(inode), PIDTYPE_PID)) {
1280 		rcu_read_unlock();
1281 		return -EPERM;
1282 	}
1283 	rcu_read_unlock();
1284 
1285 	if (*ppos != 0) {
1286 		/* No partial writes. */
1287 		return -EINVAL;
1288 	}
1289 
1290 	rv = kstrtou32_from_user(buf, count, 10, &loginuid);
1291 	if (rv < 0)
1292 		return rv;
1293 
1294 	/* is userspace tring to explicitly UNSET the loginuid? */
1295 	if (loginuid == AUDIT_UID_UNSET) {
1296 		kloginuid = INVALID_UID;
1297 	} else {
1298 		kloginuid = make_kuid(file->f_cred->user_ns, loginuid);
1299 		if (!uid_valid(kloginuid))
1300 			return -EINVAL;
1301 	}
1302 
1303 	rv = audit_set_loginuid(kloginuid);
1304 	if (rv < 0)
1305 		return rv;
1306 	return count;
1307 }
1308 
1309 static const struct file_operations proc_loginuid_operations = {
1310 	.read		= proc_loginuid_read,
1311 	.write		= proc_loginuid_write,
1312 	.llseek		= generic_file_llseek,
1313 };
1314 
proc_sessionid_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)1315 static ssize_t proc_sessionid_read(struct file * file, char __user * buf,
1316 				  size_t count, loff_t *ppos)
1317 {
1318 	struct inode * inode = file_inode(file);
1319 	struct task_struct *task = get_proc_task(inode);
1320 	ssize_t length;
1321 	char tmpbuf[TMPBUFLEN];
1322 
1323 	if (!task)
1324 		return -ESRCH;
1325 	length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
1326 				audit_get_sessionid(task));
1327 	put_task_struct(task);
1328 	return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
1329 }
1330 
1331 static const struct file_operations proc_sessionid_operations = {
1332 	.read		= proc_sessionid_read,
1333 	.llseek		= generic_file_llseek,
1334 };
1335 #endif
1336 
1337 #ifdef CONFIG_FAULT_INJECTION
proc_fault_inject_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)1338 static ssize_t proc_fault_inject_read(struct file * file, char __user * buf,
1339 				      size_t count, loff_t *ppos)
1340 {
1341 	struct task_struct *task = get_proc_task(file_inode(file));
1342 	char buffer[PROC_NUMBUF];
1343 	size_t len;
1344 	int make_it_fail;
1345 
1346 	if (!task)
1347 		return -ESRCH;
1348 	make_it_fail = task->make_it_fail;
1349 	put_task_struct(task);
1350 
1351 	len = snprintf(buffer, sizeof(buffer), "%i\n", make_it_fail);
1352 
1353 	return simple_read_from_buffer(buf, count, ppos, buffer, len);
1354 }
1355 
proc_fault_inject_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)1356 static ssize_t proc_fault_inject_write(struct file * file,
1357 			const char __user * buf, size_t count, loff_t *ppos)
1358 {
1359 	struct task_struct *task;
1360 	char buffer[PROC_NUMBUF];
1361 	int make_it_fail;
1362 	int rv;
1363 
1364 	if (!capable(CAP_SYS_RESOURCE))
1365 		return -EPERM;
1366 	memset(buffer, 0, sizeof(buffer));
1367 	if (count > sizeof(buffer) - 1)
1368 		count = sizeof(buffer) - 1;
1369 	if (copy_from_user(buffer, buf, count))
1370 		return -EFAULT;
1371 	rv = kstrtoint(strstrip(buffer), 0, &make_it_fail);
1372 	if (rv < 0)
1373 		return rv;
1374 	if (make_it_fail < 0 || make_it_fail > 1)
1375 		return -EINVAL;
1376 
1377 	task = get_proc_task(file_inode(file));
1378 	if (!task)
1379 		return -ESRCH;
1380 	task->make_it_fail = make_it_fail;
1381 	put_task_struct(task);
1382 
1383 	return count;
1384 }
1385 
1386 static const struct file_operations proc_fault_inject_operations = {
1387 	.read		= proc_fault_inject_read,
1388 	.write		= proc_fault_inject_write,
1389 	.llseek		= generic_file_llseek,
1390 };
1391 
proc_fail_nth_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)1392 static ssize_t proc_fail_nth_write(struct file *file, const char __user *buf,
1393 				   size_t count, loff_t *ppos)
1394 {
1395 	struct task_struct *task;
1396 	int err;
1397 	unsigned int n;
1398 
1399 	err = kstrtouint_from_user(buf, count, 0, &n);
1400 	if (err)
1401 		return err;
1402 
1403 	task = get_proc_task(file_inode(file));
1404 	if (!task)
1405 		return -ESRCH;
1406 	task->fail_nth = n;
1407 	put_task_struct(task);
1408 
1409 	return count;
1410 }
1411 
proc_fail_nth_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)1412 static ssize_t proc_fail_nth_read(struct file *file, char __user *buf,
1413 				  size_t count, loff_t *ppos)
1414 {
1415 	struct task_struct *task;
1416 	char numbuf[PROC_NUMBUF];
1417 	ssize_t len;
1418 
1419 	task = get_proc_task(file_inode(file));
1420 	if (!task)
1421 		return -ESRCH;
1422 	len = snprintf(numbuf, sizeof(numbuf), "%u\n", task->fail_nth);
1423 	put_task_struct(task);
1424 	return simple_read_from_buffer(buf, count, ppos, numbuf, len);
1425 }
1426 
1427 static const struct file_operations proc_fail_nth_operations = {
1428 	.read		= proc_fail_nth_read,
1429 	.write		= proc_fail_nth_write,
1430 };
1431 #endif
1432 
1433 
1434 #ifdef CONFIG_SCHED_DEBUG
1435 /*
1436  * Print out various scheduling related per-task fields:
1437  */
sched_show(struct seq_file * m,void * v)1438 static int sched_show(struct seq_file *m, void *v)
1439 {
1440 	struct inode *inode = m->private;
1441 	struct pid_namespace *ns = proc_pid_ns(inode->i_sb);
1442 	struct task_struct *p;
1443 
1444 	p = get_proc_task(inode);
1445 	if (!p)
1446 		return -ESRCH;
1447 	proc_sched_show_task(p, ns, m);
1448 
1449 	put_task_struct(p);
1450 
1451 	return 0;
1452 }
1453 
1454 static ssize_t
sched_write(struct file * file,const char __user * buf,size_t count,loff_t * offset)1455 sched_write(struct file *file, const char __user *buf,
1456 	    size_t count, loff_t *offset)
1457 {
1458 	struct inode *inode = file_inode(file);
1459 	struct task_struct *p;
1460 
1461 	p = get_proc_task(inode);
1462 	if (!p)
1463 		return -ESRCH;
1464 	proc_sched_set_task(p);
1465 
1466 	put_task_struct(p);
1467 
1468 	return count;
1469 }
1470 
sched_open(struct inode * inode,struct file * filp)1471 static int sched_open(struct inode *inode, struct file *filp)
1472 {
1473 	return single_open(filp, sched_show, inode);
1474 }
1475 
1476 static const struct file_operations proc_pid_sched_operations = {
1477 	.open		= sched_open,
1478 	.read		= seq_read,
1479 	.write		= sched_write,
1480 	.llseek		= seq_lseek,
1481 	.release	= single_release,
1482 };
1483 
1484 #endif
1485 
1486 #ifdef CONFIG_SCHED_AUTOGROUP
1487 /*
1488  * Print out autogroup related information:
1489  */
sched_autogroup_show(struct seq_file * m,void * v)1490 static int sched_autogroup_show(struct seq_file *m, void *v)
1491 {
1492 	struct inode *inode = m->private;
1493 	struct task_struct *p;
1494 
1495 	p = get_proc_task(inode);
1496 	if (!p)
1497 		return -ESRCH;
1498 	proc_sched_autogroup_show_task(p, m);
1499 
1500 	put_task_struct(p);
1501 
1502 	return 0;
1503 }
1504 
1505 static ssize_t
sched_autogroup_write(struct file * file,const char __user * buf,size_t count,loff_t * offset)1506 sched_autogroup_write(struct file *file, const char __user *buf,
1507 	    size_t count, loff_t *offset)
1508 {
1509 	struct inode *inode = file_inode(file);
1510 	struct task_struct *p;
1511 	char buffer[PROC_NUMBUF];
1512 	int nice;
1513 	int err;
1514 
1515 	memset(buffer, 0, sizeof(buffer));
1516 	if (count > sizeof(buffer) - 1)
1517 		count = sizeof(buffer) - 1;
1518 	if (copy_from_user(buffer, buf, count))
1519 		return -EFAULT;
1520 
1521 	err = kstrtoint(strstrip(buffer), 0, &nice);
1522 	if (err < 0)
1523 		return err;
1524 
1525 	p = get_proc_task(inode);
1526 	if (!p)
1527 		return -ESRCH;
1528 
1529 	err = proc_sched_autogroup_set_nice(p, nice);
1530 	if (err)
1531 		count = err;
1532 
1533 	put_task_struct(p);
1534 
1535 	return count;
1536 }
1537 
sched_autogroup_open(struct inode * inode,struct file * filp)1538 static int sched_autogroup_open(struct inode *inode, struct file *filp)
1539 {
1540 	int ret;
1541 
1542 	ret = single_open(filp, sched_autogroup_show, NULL);
1543 	if (!ret) {
1544 		struct seq_file *m = filp->private_data;
1545 
1546 		m->private = inode;
1547 	}
1548 	return ret;
1549 }
1550 
1551 static const struct file_operations proc_pid_sched_autogroup_operations = {
1552 	.open		= sched_autogroup_open,
1553 	.read		= seq_read,
1554 	.write		= sched_autogroup_write,
1555 	.llseek		= seq_lseek,
1556 	.release	= single_release,
1557 };
1558 
1559 #endif /* CONFIG_SCHED_AUTOGROUP */
1560 
1561 #ifdef CONFIG_TIME_NS
timens_offsets_show(struct seq_file * m,void * v)1562 static int timens_offsets_show(struct seq_file *m, void *v)
1563 {
1564 	struct task_struct *p;
1565 
1566 	p = get_proc_task(file_inode(m->file));
1567 	if (!p)
1568 		return -ESRCH;
1569 	proc_timens_show_offsets(p, m);
1570 
1571 	put_task_struct(p);
1572 
1573 	return 0;
1574 }
1575 
timens_offsets_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)1576 static ssize_t timens_offsets_write(struct file *file, const char __user *buf,
1577 				    size_t count, loff_t *ppos)
1578 {
1579 	struct inode *inode = file_inode(file);
1580 	struct proc_timens_offset offsets[2];
1581 	char *kbuf = NULL, *pos, *next_line;
1582 	struct task_struct *p;
1583 	int ret, noffsets;
1584 
1585 	/* Only allow < page size writes at the beginning of the file */
1586 	if ((*ppos != 0) || (count >= PAGE_SIZE))
1587 		return -EINVAL;
1588 
1589 	/* Slurp in the user data */
1590 	kbuf = memdup_user_nul(buf, count);
1591 	if (IS_ERR(kbuf))
1592 		return PTR_ERR(kbuf);
1593 
1594 	/* Parse the user data */
1595 	ret = -EINVAL;
1596 	noffsets = 0;
1597 	for (pos = kbuf; pos; pos = next_line) {
1598 		struct proc_timens_offset *off = &offsets[noffsets];
1599 		char clock[10];
1600 		int err;
1601 
1602 		/* Find the end of line and ensure we don't look past it */
1603 		next_line = strchr(pos, '\n');
1604 		if (next_line) {
1605 			*next_line = '\0';
1606 			next_line++;
1607 			if (*next_line == '\0')
1608 				next_line = NULL;
1609 		}
1610 
1611 		err = sscanf(pos, "%9s %lld %lu", clock,
1612 				&off->val.tv_sec, &off->val.tv_nsec);
1613 		if (err != 3 || off->val.tv_nsec >= NSEC_PER_SEC)
1614 			goto out;
1615 
1616 		clock[sizeof(clock) - 1] = 0;
1617 		if (strcmp(clock, "monotonic") == 0 ||
1618 		    strcmp(clock, __stringify(CLOCK_MONOTONIC)) == 0)
1619 			off->clockid = CLOCK_MONOTONIC;
1620 		else if (strcmp(clock, "boottime") == 0 ||
1621 			 strcmp(clock, __stringify(CLOCK_BOOTTIME)) == 0)
1622 			off->clockid = CLOCK_BOOTTIME;
1623 		else
1624 			goto out;
1625 
1626 		noffsets++;
1627 		if (noffsets == ARRAY_SIZE(offsets)) {
1628 			if (next_line)
1629 				count = next_line - kbuf;
1630 			break;
1631 		}
1632 	}
1633 
1634 	ret = -ESRCH;
1635 	p = get_proc_task(inode);
1636 	if (!p)
1637 		goto out;
1638 	ret = proc_timens_set_offset(file, p, offsets, noffsets);
1639 	put_task_struct(p);
1640 	if (ret)
1641 		goto out;
1642 
1643 	ret = count;
1644 out:
1645 	kfree(kbuf);
1646 	return ret;
1647 }
1648 
timens_offsets_open(struct inode * inode,struct file * filp)1649 static int timens_offsets_open(struct inode *inode, struct file *filp)
1650 {
1651 	return single_open(filp, timens_offsets_show, inode);
1652 }
1653 
1654 static const struct file_operations proc_timens_offsets_operations = {
1655 	.open		= timens_offsets_open,
1656 	.read		= seq_read,
1657 	.write		= timens_offsets_write,
1658 	.llseek		= seq_lseek,
1659 	.release	= single_release,
1660 };
1661 #endif /* CONFIG_TIME_NS */
1662 
comm_write(struct file * file,const char __user * buf,size_t count,loff_t * offset)1663 static ssize_t comm_write(struct file *file, const char __user *buf,
1664 				size_t count, loff_t *offset)
1665 {
1666 	struct inode *inode = file_inode(file);
1667 	struct task_struct *p;
1668 	char buffer[TASK_COMM_LEN];
1669 	const size_t maxlen = sizeof(buffer) - 1;
1670 
1671 	memset(buffer, 0, sizeof(buffer));
1672 	if (copy_from_user(buffer, buf, count > maxlen ? maxlen : count))
1673 		return -EFAULT;
1674 
1675 	p = get_proc_task(inode);
1676 	if (!p)
1677 		return -ESRCH;
1678 
1679 	if (same_thread_group(current, p))
1680 		set_task_comm(p, buffer);
1681 	else
1682 		count = -EINVAL;
1683 
1684 	put_task_struct(p);
1685 
1686 	return count;
1687 }
1688 
comm_show(struct seq_file * m,void * v)1689 static int comm_show(struct seq_file *m, void *v)
1690 {
1691 	struct inode *inode = m->private;
1692 	struct task_struct *p;
1693 
1694 	p = get_proc_task(inode);
1695 	if (!p)
1696 		return -ESRCH;
1697 
1698 	proc_task_name(m, p, false);
1699 	seq_putc(m, '\n');
1700 
1701 	put_task_struct(p);
1702 
1703 	return 0;
1704 }
1705 
comm_open(struct inode * inode,struct file * filp)1706 static int comm_open(struct inode *inode, struct file *filp)
1707 {
1708 	return single_open(filp, comm_show, inode);
1709 }
1710 
1711 static const struct file_operations proc_pid_set_comm_operations = {
1712 	.open		= comm_open,
1713 	.read		= seq_read,
1714 	.write		= comm_write,
1715 	.llseek		= seq_lseek,
1716 	.release	= single_release,
1717 };
1718 
proc_exe_link(struct dentry * dentry,struct path * exe_path)1719 static int proc_exe_link(struct dentry *dentry, struct path *exe_path)
1720 {
1721 	struct task_struct *task;
1722 	struct file *exe_file;
1723 
1724 	task = get_proc_task(d_inode(dentry));
1725 	if (!task)
1726 		return -ENOENT;
1727 	exe_file = get_task_exe_file(task);
1728 	put_task_struct(task);
1729 	if (exe_file) {
1730 		*exe_path = exe_file->f_path;
1731 		path_get(&exe_file->f_path);
1732 		fput(exe_file);
1733 		return 0;
1734 	} else
1735 		return -ENOENT;
1736 }
1737 
proc_pid_get_link(struct dentry * dentry,struct inode * inode,struct delayed_call * done)1738 static const char *proc_pid_get_link(struct dentry *dentry,
1739 				     struct inode *inode,
1740 				     struct delayed_call *done)
1741 {
1742 	struct path path;
1743 	int error = -EACCES;
1744 
1745 	if (!dentry)
1746 		return ERR_PTR(-ECHILD);
1747 
1748 	/* Are we allowed to snoop on the tasks file descriptors? */
1749 	if (!proc_fd_access_allowed(inode))
1750 		goto out;
1751 
1752 	error = PROC_I(inode)->op.proc_get_link(dentry, &path);
1753 	if (error)
1754 		goto out;
1755 
1756 	error = nd_jump_link(&path);
1757 out:
1758 	return ERR_PTR(error);
1759 }
1760 
do_proc_readlink(struct path * path,char __user * buffer,int buflen)1761 static int do_proc_readlink(struct path *path, char __user *buffer, int buflen)
1762 {
1763 	char *tmp = (char *)__get_free_page(GFP_KERNEL);
1764 	char *pathname;
1765 	int len;
1766 
1767 	if (!tmp)
1768 		return -ENOMEM;
1769 
1770 	pathname = d_path(path, tmp, PAGE_SIZE);
1771 	len = PTR_ERR(pathname);
1772 	if (IS_ERR(pathname))
1773 		goto out;
1774 	len = tmp + PAGE_SIZE - 1 - pathname;
1775 
1776 	if (len > buflen)
1777 		len = buflen;
1778 	if (copy_to_user(buffer, pathname, len))
1779 		len = -EFAULT;
1780  out:
1781 	free_page((unsigned long)tmp);
1782 	return len;
1783 }
1784 
proc_pid_readlink(struct dentry * dentry,char __user * buffer,int buflen)1785 static int proc_pid_readlink(struct dentry * dentry, char __user * buffer, int buflen)
1786 {
1787 	int error = -EACCES;
1788 	struct inode *inode = d_inode(dentry);
1789 	struct path path;
1790 
1791 	/* Are we allowed to snoop on the tasks file descriptors? */
1792 	if (!proc_fd_access_allowed(inode))
1793 		goto out;
1794 
1795 	error = PROC_I(inode)->op.proc_get_link(dentry, &path);
1796 	if (error)
1797 		goto out;
1798 
1799 	error = do_proc_readlink(&path, buffer, buflen);
1800 	path_put(&path);
1801 out:
1802 	return error;
1803 }
1804 
1805 const struct inode_operations proc_pid_link_inode_operations = {
1806 	.readlink	= proc_pid_readlink,
1807 	.get_link	= proc_pid_get_link,
1808 	.setattr	= proc_setattr,
1809 };
1810 
1811 
1812 /* building an inode */
1813 
task_dump_owner(struct task_struct * task,umode_t mode,kuid_t * ruid,kgid_t * rgid)1814 void task_dump_owner(struct task_struct *task, umode_t mode,
1815 		     kuid_t *ruid, kgid_t *rgid)
1816 {
1817 	/* Depending on the state of dumpable compute who should own a
1818 	 * proc file for a task.
1819 	 */
1820 	const struct cred *cred;
1821 	kuid_t uid;
1822 	kgid_t gid;
1823 
1824 	if (unlikely(task->flags & PF_KTHREAD)) {
1825 		*ruid = GLOBAL_ROOT_UID;
1826 		*rgid = GLOBAL_ROOT_GID;
1827 		return;
1828 	}
1829 
1830 	/* Default to the tasks effective ownership */
1831 	rcu_read_lock();
1832 	cred = __task_cred(task);
1833 	uid = cred->euid;
1834 	gid = cred->egid;
1835 	rcu_read_unlock();
1836 
1837 	/*
1838 	 * Before the /proc/pid/status file was created the only way to read
1839 	 * the effective uid of a /process was to stat /proc/pid.  Reading
1840 	 * /proc/pid/status is slow enough that procps and other packages
1841 	 * kept stating /proc/pid.  To keep the rules in /proc simple I have
1842 	 * made this apply to all per process world readable and executable
1843 	 * directories.
1844 	 */
1845 	if (mode != (S_IFDIR|S_IRUGO|S_IXUGO)) {
1846 		struct mm_struct *mm;
1847 		task_lock(task);
1848 		mm = task->mm;
1849 		/* Make non-dumpable tasks owned by some root */
1850 		if (mm) {
1851 			if (get_dumpable(mm) != SUID_DUMP_USER) {
1852 				struct user_namespace *user_ns = mm->user_ns;
1853 
1854 				uid = make_kuid(user_ns, 0);
1855 				if (!uid_valid(uid))
1856 					uid = GLOBAL_ROOT_UID;
1857 
1858 				gid = make_kgid(user_ns, 0);
1859 				if (!gid_valid(gid))
1860 					gid = GLOBAL_ROOT_GID;
1861 			}
1862 		} else {
1863 			uid = GLOBAL_ROOT_UID;
1864 			gid = GLOBAL_ROOT_GID;
1865 		}
1866 		task_unlock(task);
1867 	}
1868 	*ruid = uid;
1869 	*rgid = gid;
1870 }
1871 
proc_pid_evict_inode(struct proc_inode * ei)1872 void proc_pid_evict_inode(struct proc_inode *ei)
1873 {
1874 	struct pid *pid = ei->pid;
1875 
1876 	if (S_ISDIR(ei->vfs_inode.i_mode)) {
1877 		spin_lock(&pid->lock);
1878 		hlist_del_init_rcu(&ei->sibling_inodes);
1879 		spin_unlock(&pid->lock);
1880 	}
1881 
1882 	put_pid(pid);
1883 }
1884 
proc_pid_make_inode(struct super_block * sb,struct task_struct * task,umode_t mode)1885 struct inode *proc_pid_make_inode(struct super_block *sb,
1886 				  struct task_struct *task, umode_t mode)
1887 {
1888 	struct inode * inode;
1889 	struct proc_inode *ei;
1890 	struct pid *pid;
1891 
1892 	/* We need a new inode */
1893 
1894 	inode = new_inode(sb);
1895 	if (!inode)
1896 		goto out;
1897 
1898 	/* Common stuff */
1899 	ei = PROC_I(inode);
1900 	inode->i_mode = mode;
1901 	inode->i_ino = get_next_ino();
1902 	inode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode);
1903 	inode->i_op = &proc_def_inode_operations;
1904 
1905 	/*
1906 	 * grab the reference to task.
1907 	 */
1908 	pid = get_task_pid(task, PIDTYPE_PID);
1909 	if (!pid)
1910 		goto out_unlock;
1911 
1912 	/* Let the pid remember us for quick removal */
1913 	ei->pid = pid;
1914 
1915 	task_dump_owner(task, 0, &inode->i_uid, &inode->i_gid);
1916 	security_task_to_inode(task, inode);
1917 
1918 out:
1919 	return inode;
1920 
1921 out_unlock:
1922 	iput(inode);
1923 	return NULL;
1924 }
1925 
1926 /*
1927  * Generating an inode and adding it into @pid->inodes, so that task will
1928  * invalidate inode's dentry before being released.
1929  *
1930  * This helper is used for creating dir-type entries under '/proc' and
1931  * '/proc/<tgid>/task'. Other entries(eg. fd, stat) under '/proc/<tgid>'
1932  * can be released by invalidating '/proc/<tgid>' dentry.
1933  * In theory, dentries under '/proc/<tgid>/task' can also be released by
1934  * invalidating '/proc/<tgid>' dentry, we reserve it to handle single
1935  * thread exiting situation: Any one of threads should invalidate its
1936  * '/proc/<tgid>/task/<pid>' dentry before released.
1937  */
proc_pid_make_base_inode(struct super_block * sb,struct task_struct * task,umode_t mode)1938 static struct inode *proc_pid_make_base_inode(struct super_block *sb,
1939 				struct task_struct *task, umode_t mode)
1940 {
1941 	struct inode *inode;
1942 	struct proc_inode *ei;
1943 	struct pid *pid;
1944 
1945 	inode = proc_pid_make_inode(sb, task, mode);
1946 	if (!inode)
1947 		return NULL;
1948 
1949 	/* Let proc_flush_pid find this directory inode */
1950 	ei = PROC_I(inode);
1951 	pid = ei->pid;
1952 	spin_lock(&pid->lock);
1953 	hlist_add_head_rcu(&ei->sibling_inodes, &pid->inodes);
1954 	spin_unlock(&pid->lock);
1955 
1956 	return inode;
1957 }
1958 
pid_getattr(const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)1959 int pid_getattr(const struct path *path, struct kstat *stat,
1960 		u32 request_mask, unsigned int query_flags)
1961 {
1962 	struct inode *inode = d_inode(path->dentry);
1963 	struct proc_fs_info *fs_info = proc_sb_info(inode->i_sb);
1964 	struct task_struct *task;
1965 
1966 	generic_fillattr(inode, stat);
1967 
1968 	stat->uid = GLOBAL_ROOT_UID;
1969 	stat->gid = GLOBAL_ROOT_GID;
1970 	rcu_read_lock();
1971 	task = pid_task(proc_pid(inode), PIDTYPE_PID);
1972 	if (task) {
1973 		if (!has_pid_permissions(fs_info, task, HIDEPID_INVISIBLE)) {
1974 			rcu_read_unlock();
1975 			/*
1976 			 * This doesn't prevent learning whether PID exists,
1977 			 * it only makes getattr() consistent with readdir().
1978 			 */
1979 			return -ENOENT;
1980 		}
1981 		task_dump_owner(task, inode->i_mode, &stat->uid, &stat->gid);
1982 	}
1983 	rcu_read_unlock();
1984 	return 0;
1985 }
1986 
1987 /* dentry stuff */
1988 
1989 /*
1990  * Set <pid>/... inode ownership (can change due to setuid(), etc.)
1991  */
pid_update_inode(struct task_struct * task,struct inode * inode)1992 void pid_update_inode(struct task_struct *task, struct inode *inode)
1993 {
1994 	task_dump_owner(task, inode->i_mode, &inode->i_uid, &inode->i_gid);
1995 
1996 	inode->i_mode &= ~(S_ISUID | S_ISGID);
1997 	security_task_to_inode(task, inode);
1998 }
1999 
2000 /*
2001  * Rewrite the inode's ownerships here because the owning task may have
2002  * performed a setuid(), etc.
2003  *
2004  */
pid_revalidate(struct dentry * dentry,unsigned int flags)2005 static int pid_revalidate(struct dentry *dentry, unsigned int flags)
2006 {
2007 	struct inode *inode;
2008 	struct task_struct *task;
2009 
2010 	if (flags & LOOKUP_RCU)
2011 		return -ECHILD;
2012 
2013 	inode = d_inode(dentry);
2014 	task = get_proc_task(inode);
2015 
2016 	if (task) {
2017 		pid_update_inode(task, inode);
2018 		put_task_struct(task);
2019 		return 1;
2020 	}
2021 	return 0;
2022 }
2023 
proc_inode_is_dead(struct inode * inode)2024 static inline bool proc_inode_is_dead(struct inode *inode)
2025 {
2026 	return !proc_pid(inode)->tasks[PIDTYPE_PID].first;
2027 }
2028 
pid_delete_dentry(const struct dentry * dentry)2029 int pid_delete_dentry(const struct dentry *dentry)
2030 {
2031 	/* Is the task we represent dead?
2032 	 * If so, then don't put the dentry on the lru list,
2033 	 * kill it immediately.
2034 	 */
2035 	return proc_inode_is_dead(d_inode(dentry));
2036 }
2037 
2038 const struct dentry_operations pid_dentry_operations =
2039 {
2040 	.d_revalidate	= pid_revalidate,
2041 	.d_delete	= pid_delete_dentry,
2042 };
2043 
2044 /* Lookups */
2045 
2046 /*
2047  * Fill a directory entry.
2048  *
2049  * If possible create the dcache entry and derive our inode number and
2050  * file type from dcache entry.
2051  *
2052  * Since all of the proc inode numbers are dynamically generated, the inode
2053  * numbers do not exist until the inode is cache.  This means creating the
2054  * the dcache entry in readdir is necessary to keep the inode numbers
2055  * reported by readdir in sync with the inode numbers reported
2056  * by stat.
2057  */
proc_fill_cache(struct file * file,struct dir_context * ctx,const char * name,unsigned int len,instantiate_t instantiate,struct task_struct * task,const void * ptr)2058 bool proc_fill_cache(struct file *file, struct dir_context *ctx,
2059 	const char *name, unsigned int len,
2060 	instantiate_t instantiate, struct task_struct *task, const void *ptr)
2061 {
2062 	struct dentry *child, *dir = file->f_path.dentry;
2063 	struct qstr qname = QSTR_INIT(name, len);
2064 	struct inode *inode;
2065 	unsigned type = DT_UNKNOWN;
2066 	ino_t ino = 1;
2067 
2068 	child = d_hash_and_lookup(dir, &qname);
2069 	if (!child) {
2070 		DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
2071 		child = d_alloc_parallel(dir, &qname, &wq);
2072 		if (IS_ERR(child))
2073 			goto end_instantiate;
2074 		if (d_in_lookup(child)) {
2075 			struct dentry *res;
2076 			res = instantiate(child, task, ptr);
2077 			d_lookup_done(child);
2078 			if (unlikely(res)) {
2079 				dput(child);
2080 				child = res;
2081 				if (IS_ERR(child))
2082 					goto end_instantiate;
2083 			}
2084 		}
2085 	}
2086 	inode = d_inode(child);
2087 	ino = inode->i_ino;
2088 	type = inode->i_mode >> 12;
2089 	dput(child);
2090 end_instantiate:
2091 	return dir_emit(ctx, name, len, ino, type);
2092 }
2093 
2094 /*
2095  * dname_to_vma_addr - maps a dentry name into two unsigned longs
2096  * which represent vma start and end addresses.
2097  */
dname_to_vma_addr(struct dentry * dentry,unsigned long * start,unsigned long * end)2098 static int dname_to_vma_addr(struct dentry *dentry,
2099 			     unsigned long *start, unsigned long *end)
2100 {
2101 	const char *str = dentry->d_name.name;
2102 	unsigned long long sval, eval;
2103 	unsigned int len;
2104 
2105 	if (str[0] == '0' && str[1] != '-')
2106 		return -EINVAL;
2107 	len = _parse_integer(str, 16, &sval);
2108 	if (len & KSTRTOX_OVERFLOW)
2109 		return -EINVAL;
2110 	if (sval != (unsigned long)sval)
2111 		return -EINVAL;
2112 	str += len;
2113 
2114 	if (*str != '-')
2115 		return -EINVAL;
2116 	str++;
2117 
2118 	if (str[0] == '0' && str[1])
2119 		return -EINVAL;
2120 	len = _parse_integer(str, 16, &eval);
2121 	if (len & KSTRTOX_OVERFLOW)
2122 		return -EINVAL;
2123 	if (eval != (unsigned long)eval)
2124 		return -EINVAL;
2125 	str += len;
2126 
2127 	if (*str != '\0')
2128 		return -EINVAL;
2129 
2130 	*start = sval;
2131 	*end = eval;
2132 
2133 	return 0;
2134 }
2135 
map_files_d_revalidate(struct dentry * dentry,unsigned int flags)2136 static int map_files_d_revalidate(struct dentry *dentry, unsigned int flags)
2137 {
2138 	unsigned long vm_start, vm_end;
2139 	bool exact_vma_exists = false;
2140 	struct mm_struct *mm = NULL;
2141 	struct task_struct *task;
2142 	struct inode *inode;
2143 	int status = 0;
2144 
2145 	if (flags & LOOKUP_RCU)
2146 		return -ECHILD;
2147 
2148 	inode = d_inode(dentry);
2149 	task = get_proc_task(inode);
2150 	if (!task)
2151 		goto out_notask;
2152 
2153 	mm = mm_access(task, PTRACE_MODE_READ_FSCREDS);
2154 	if (IS_ERR_OR_NULL(mm))
2155 		goto out;
2156 
2157 	if (!dname_to_vma_addr(dentry, &vm_start, &vm_end)) {
2158 		status = mmap_read_lock_killable(mm);
2159 		if (!status) {
2160 			exact_vma_exists = !!find_exact_vma(mm, vm_start,
2161 							    vm_end);
2162 			mmap_read_unlock(mm);
2163 		}
2164 	}
2165 
2166 	mmput(mm);
2167 
2168 	if (exact_vma_exists) {
2169 		task_dump_owner(task, 0, &inode->i_uid, &inode->i_gid);
2170 
2171 		security_task_to_inode(task, inode);
2172 		status = 1;
2173 	}
2174 
2175 out:
2176 	put_task_struct(task);
2177 
2178 out_notask:
2179 	return status;
2180 }
2181 
2182 static const struct dentry_operations tid_map_files_dentry_operations = {
2183 	.d_revalidate	= map_files_d_revalidate,
2184 	.d_delete	= pid_delete_dentry,
2185 };
2186 
map_files_get_link(struct dentry * dentry,struct path * path)2187 static int map_files_get_link(struct dentry *dentry, struct path *path)
2188 {
2189 	unsigned long vm_start, vm_end;
2190 	struct vm_area_struct *vma;
2191 	struct task_struct *task;
2192 	struct mm_struct *mm;
2193 	int rc;
2194 
2195 	rc = -ENOENT;
2196 	task = get_proc_task(d_inode(dentry));
2197 	if (!task)
2198 		goto out;
2199 
2200 	mm = get_task_mm(task);
2201 	put_task_struct(task);
2202 	if (!mm)
2203 		goto out;
2204 
2205 	rc = dname_to_vma_addr(dentry, &vm_start, &vm_end);
2206 	if (rc)
2207 		goto out_mmput;
2208 
2209 	rc = mmap_read_lock_killable(mm);
2210 	if (rc)
2211 		goto out_mmput;
2212 
2213 	rc = -ENOENT;
2214 	vma = find_exact_vma(mm, vm_start, vm_end);
2215 	if (vma && vma->vm_file) {
2216 		*path = vma->vm_file->f_path;
2217 		path_get(path);
2218 		rc = 0;
2219 	}
2220 	mmap_read_unlock(mm);
2221 
2222 out_mmput:
2223 	mmput(mm);
2224 out:
2225 	return rc;
2226 }
2227 
2228 struct map_files_info {
2229 	unsigned long	start;
2230 	unsigned long	end;
2231 	fmode_t		mode;
2232 };
2233 
2234 /*
2235  * Only allow CAP_SYS_ADMIN and CAP_CHECKPOINT_RESTORE to follow the links, due
2236  * to concerns about how the symlinks may be used to bypass permissions on
2237  * ancestor directories in the path to the file in question.
2238  */
2239 static const char *
proc_map_files_get_link(struct dentry * dentry,struct inode * inode,struct delayed_call * done)2240 proc_map_files_get_link(struct dentry *dentry,
2241 			struct inode *inode,
2242 		        struct delayed_call *done)
2243 {
2244 	if (!checkpoint_restore_ns_capable(&init_user_ns))
2245 		return ERR_PTR(-EPERM);
2246 
2247 	return proc_pid_get_link(dentry, inode, done);
2248 }
2249 
2250 /*
2251  * Identical to proc_pid_link_inode_operations except for get_link()
2252  */
2253 static const struct inode_operations proc_map_files_link_inode_operations = {
2254 	.readlink	= proc_pid_readlink,
2255 	.get_link	= proc_map_files_get_link,
2256 	.setattr	= proc_setattr,
2257 };
2258 
2259 static struct dentry *
proc_map_files_instantiate(struct dentry * dentry,struct task_struct * task,const void * ptr)2260 proc_map_files_instantiate(struct dentry *dentry,
2261 			   struct task_struct *task, const void *ptr)
2262 {
2263 	fmode_t mode = (fmode_t)(unsigned long)ptr;
2264 	struct proc_inode *ei;
2265 	struct inode *inode;
2266 
2267 	inode = proc_pid_make_inode(dentry->d_sb, task, S_IFLNK |
2268 				    ((mode & FMODE_READ ) ? S_IRUSR : 0) |
2269 				    ((mode & FMODE_WRITE) ? S_IWUSR : 0));
2270 	if (!inode)
2271 		return ERR_PTR(-ENOENT);
2272 
2273 	ei = PROC_I(inode);
2274 	ei->op.proc_get_link = map_files_get_link;
2275 
2276 	inode->i_op = &proc_map_files_link_inode_operations;
2277 	inode->i_size = 64;
2278 
2279 	d_set_d_op(dentry, &tid_map_files_dentry_operations);
2280 	return d_splice_alias(inode, dentry);
2281 }
2282 
proc_map_files_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)2283 static struct dentry *proc_map_files_lookup(struct inode *dir,
2284 		struct dentry *dentry, unsigned int flags)
2285 {
2286 	unsigned long vm_start, vm_end;
2287 	struct vm_area_struct *vma;
2288 	struct task_struct *task;
2289 	struct dentry *result;
2290 	struct mm_struct *mm;
2291 
2292 	result = ERR_PTR(-ENOENT);
2293 	task = get_proc_task(dir);
2294 	if (!task)
2295 		goto out;
2296 
2297 	result = ERR_PTR(-EACCES);
2298 	if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
2299 		goto out_put_task;
2300 
2301 	result = ERR_PTR(-ENOENT);
2302 	if (dname_to_vma_addr(dentry, &vm_start, &vm_end))
2303 		goto out_put_task;
2304 
2305 	mm = get_task_mm(task);
2306 	if (!mm)
2307 		goto out_put_task;
2308 
2309 	result = ERR_PTR(-EINTR);
2310 	if (mmap_read_lock_killable(mm))
2311 		goto out_put_mm;
2312 
2313 	result = ERR_PTR(-ENOENT);
2314 	vma = find_exact_vma(mm, vm_start, vm_end);
2315 	if (!vma)
2316 		goto out_no_vma;
2317 
2318 	if (vma->vm_file)
2319 		result = proc_map_files_instantiate(dentry, task,
2320 				(void *)(unsigned long)vma->vm_file->f_mode);
2321 
2322 out_no_vma:
2323 	mmap_read_unlock(mm);
2324 out_put_mm:
2325 	mmput(mm);
2326 out_put_task:
2327 	put_task_struct(task);
2328 out:
2329 	return result;
2330 }
2331 
2332 static const struct inode_operations proc_map_files_inode_operations = {
2333 	.lookup		= proc_map_files_lookup,
2334 	.permission	= proc_fd_permission,
2335 	.setattr	= proc_setattr,
2336 };
2337 
2338 static int
proc_map_files_readdir(struct file * file,struct dir_context * ctx)2339 proc_map_files_readdir(struct file *file, struct dir_context *ctx)
2340 {
2341 	struct vm_area_struct *vma;
2342 	struct task_struct *task;
2343 	struct mm_struct *mm;
2344 	unsigned long nr_files, pos, i;
2345 	GENRADIX(struct map_files_info) fa;
2346 	struct map_files_info *p;
2347 	int ret;
2348 
2349 	genradix_init(&fa);
2350 
2351 	ret = -ENOENT;
2352 	task = get_proc_task(file_inode(file));
2353 	if (!task)
2354 		goto out;
2355 
2356 	ret = -EACCES;
2357 	if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
2358 		goto out_put_task;
2359 
2360 	ret = 0;
2361 	if (!dir_emit_dots(file, ctx))
2362 		goto out_put_task;
2363 
2364 	mm = get_task_mm(task);
2365 	if (!mm)
2366 		goto out_put_task;
2367 
2368 	ret = mmap_read_lock_killable(mm);
2369 	if (ret) {
2370 		mmput(mm);
2371 		goto out_put_task;
2372 	}
2373 
2374 	nr_files = 0;
2375 
2376 	/*
2377 	 * We need two passes here:
2378 	 *
2379 	 *  1) Collect vmas of mapped files with mmap_lock taken
2380 	 *  2) Release mmap_lock and instantiate entries
2381 	 *
2382 	 * otherwise we get lockdep complained, since filldir()
2383 	 * routine might require mmap_lock taken in might_fault().
2384 	 */
2385 
2386 	for (vma = mm->mmap, pos = 2; vma; vma = vma->vm_next) {
2387 		if (!vma->vm_file)
2388 			continue;
2389 		if (++pos <= ctx->pos)
2390 			continue;
2391 
2392 		p = genradix_ptr_alloc(&fa, nr_files++, GFP_KERNEL);
2393 		if (!p) {
2394 			ret = -ENOMEM;
2395 			mmap_read_unlock(mm);
2396 			mmput(mm);
2397 			goto out_put_task;
2398 		}
2399 
2400 		p->start = vma->vm_start;
2401 		p->end = vma->vm_end;
2402 		p->mode = vma->vm_file->f_mode;
2403 	}
2404 	mmap_read_unlock(mm);
2405 	mmput(mm);
2406 
2407 	for (i = 0; i < nr_files; i++) {
2408 		char buf[4 * sizeof(long) + 2];	/* max: %lx-%lx\0 */
2409 		unsigned int len;
2410 
2411 		p = genradix_ptr(&fa, i);
2412 		len = snprintf(buf, sizeof(buf), "%lx-%lx", p->start, p->end);
2413 		if (!proc_fill_cache(file, ctx,
2414 				      buf, len,
2415 				      proc_map_files_instantiate,
2416 				      task,
2417 				      (void *)(unsigned long)p->mode))
2418 			break;
2419 		ctx->pos++;
2420 	}
2421 
2422 out_put_task:
2423 	put_task_struct(task);
2424 out:
2425 	genradix_free(&fa);
2426 	return ret;
2427 }
2428 
2429 static const struct file_operations proc_map_files_operations = {
2430 	.read		= generic_read_dir,
2431 	.iterate_shared	= proc_map_files_readdir,
2432 	.llseek		= generic_file_llseek,
2433 };
2434 
2435 #if defined(CONFIG_CHECKPOINT_RESTORE) && defined(CONFIG_POSIX_TIMERS)
2436 struct timers_private {
2437 	struct pid *pid;
2438 	struct task_struct *task;
2439 	struct sighand_struct *sighand;
2440 	struct pid_namespace *ns;
2441 	unsigned long flags;
2442 };
2443 
timers_start(struct seq_file * m,loff_t * pos)2444 static void *timers_start(struct seq_file *m, loff_t *pos)
2445 {
2446 	struct timers_private *tp = m->private;
2447 
2448 	tp->task = get_pid_task(tp->pid, PIDTYPE_PID);
2449 	if (!tp->task)
2450 		return ERR_PTR(-ESRCH);
2451 
2452 	tp->sighand = lock_task_sighand(tp->task, &tp->flags);
2453 	if (!tp->sighand)
2454 		return ERR_PTR(-ESRCH);
2455 
2456 	return seq_list_start(&tp->task->signal->posix_timers, *pos);
2457 }
2458 
timers_next(struct seq_file * m,void * v,loff_t * pos)2459 static void *timers_next(struct seq_file *m, void *v, loff_t *pos)
2460 {
2461 	struct timers_private *tp = m->private;
2462 	return seq_list_next(v, &tp->task->signal->posix_timers, pos);
2463 }
2464 
timers_stop(struct seq_file * m,void * v)2465 static void timers_stop(struct seq_file *m, void *v)
2466 {
2467 	struct timers_private *tp = m->private;
2468 
2469 	if (tp->sighand) {
2470 		unlock_task_sighand(tp->task, &tp->flags);
2471 		tp->sighand = NULL;
2472 	}
2473 
2474 	if (tp->task) {
2475 		put_task_struct(tp->task);
2476 		tp->task = NULL;
2477 	}
2478 }
2479 
show_timer(struct seq_file * m,void * v)2480 static int show_timer(struct seq_file *m, void *v)
2481 {
2482 	struct k_itimer *timer;
2483 	struct timers_private *tp = m->private;
2484 	int notify;
2485 	static const char * const nstr[] = {
2486 		[SIGEV_SIGNAL] = "signal",
2487 		[SIGEV_NONE] = "none",
2488 		[SIGEV_THREAD] = "thread",
2489 	};
2490 
2491 	timer = list_entry((struct list_head *)v, struct k_itimer, list);
2492 	notify = timer->it_sigev_notify;
2493 
2494 	seq_printf(m, "ID: %d\n", timer->it_id);
2495 	seq_printf(m, "signal: %d/%px\n",
2496 		   timer->sigq->info.si_signo,
2497 		   timer->sigq->info.si_value.sival_ptr);
2498 	seq_printf(m, "notify: %s/%s.%d\n",
2499 		   nstr[notify & ~SIGEV_THREAD_ID],
2500 		   (notify & SIGEV_THREAD_ID) ? "tid" : "pid",
2501 		   pid_nr_ns(timer->it_pid, tp->ns));
2502 	seq_printf(m, "ClockID: %d\n", timer->it_clock);
2503 
2504 	return 0;
2505 }
2506 
2507 static const struct seq_operations proc_timers_seq_ops = {
2508 	.start	= timers_start,
2509 	.next	= timers_next,
2510 	.stop	= timers_stop,
2511 	.show	= show_timer,
2512 };
2513 
proc_timers_open(struct inode * inode,struct file * file)2514 static int proc_timers_open(struct inode *inode, struct file *file)
2515 {
2516 	struct timers_private *tp;
2517 
2518 	tp = __seq_open_private(file, &proc_timers_seq_ops,
2519 			sizeof(struct timers_private));
2520 	if (!tp)
2521 		return -ENOMEM;
2522 
2523 	tp->pid = proc_pid(inode);
2524 	tp->ns = proc_pid_ns(inode->i_sb);
2525 	return 0;
2526 }
2527 
2528 static const struct file_operations proc_timers_operations = {
2529 	.open		= proc_timers_open,
2530 	.read		= seq_read,
2531 	.llseek		= seq_lseek,
2532 	.release	= seq_release_private,
2533 };
2534 #endif
2535 
timerslack_ns_write(struct file * file,const char __user * buf,size_t count,loff_t * offset)2536 static ssize_t timerslack_ns_write(struct file *file, const char __user *buf,
2537 					size_t count, loff_t *offset)
2538 {
2539 	struct inode *inode = file_inode(file);
2540 	struct task_struct *p;
2541 	u64 slack_ns;
2542 	int err;
2543 
2544 	err = kstrtoull_from_user(buf, count, 10, &slack_ns);
2545 	if (err < 0)
2546 		return err;
2547 
2548 	p = get_proc_task(inode);
2549 	if (!p)
2550 		return -ESRCH;
2551 
2552 	if (p != current) {
2553 		rcu_read_lock();
2554 		if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
2555 			rcu_read_unlock();
2556 			count = -EPERM;
2557 			goto out;
2558 		}
2559 		rcu_read_unlock();
2560 
2561 		err = security_task_setscheduler(p);
2562 		if (err) {
2563 			count = err;
2564 			goto out;
2565 		}
2566 	}
2567 
2568 	task_lock(p);
2569 	if (slack_ns == 0)
2570 		p->timer_slack_ns = p->default_timer_slack_ns;
2571 	else
2572 		p->timer_slack_ns = slack_ns;
2573 	task_unlock(p);
2574 
2575 out:
2576 	put_task_struct(p);
2577 
2578 	return count;
2579 }
2580 
timerslack_ns_show(struct seq_file * m,void * v)2581 static int timerslack_ns_show(struct seq_file *m, void *v)
2582 {
2583 	struct inode *inode = m->private;
2584 	struct task_struct *p;
2585 	int err = 0;
2586 
2587 	p = get_proc_task(inode);
2588 	if (!p)
2589 		return -ESRCH;
2590 
2591 	if (p != current) {
2592 		rcu_read_lock();
2593 		if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
2594 			rcu_read_unlock();
2595 			err = -EPERM;
2596 			goto out;
2597 		}
2598 		rcu_read_unlock();
2599 
2600 		err = security_task_getscheduler(p);
2601 		if (err)
2602 			goto out;
2603 	}
2604 
2605 	task_lock(p);
2606 	seq_printf(m, "%llu\n", p->timer_slack_ns);
2607 	task_unlock(p);
2608 
2609 out:
2610 	put_task_struct(p);
2611 
2612 	return err;
2613 }
2614 
timerslack_ns_open(struct inode * inode,struct file * filp)2615 static int timerslack_ns_open(struct inode *inode, struct file *filp)
2616 {
2617 	return single_open(filp, timerslack_ns_show, inode);
2618 }
2619 
2620 static const struct file_operations proc_pid_set_timerslack_ns_operations = {
2621 	.open		= timerslack_ns_open,
2622 	.read		= seq_read,
2623 	.write		= timerslack_ns_write,
2624 	.llseek		= seq_lseek,
2625 	.release	= single_release,
2626 };
2627 
proc_pident_instantiate(struct dentry * dentry,struct task_struct * task,const void * ptr)2628 static struct dentry *proc_pident_instantiate(struct dentry *dentry,
2629 	struct task_struct *task, const void *ptr)
2630 {
2631 	const struct pid_entry *p = ptr;
2632 	struct inode *inode;
2633 	struct proc_inode *ei;
2634 
2635 	inode = proc_pid_make_inode(dentry->d_sb, task, p->mode);
2636 	if (!inode)
2637 		return ERR_PTR(-ENOENT);
2638 
2639 	ei = PROC_I(inode);
2640 	if (S_ISDIR(inode->i_mode))
2641 		set_nlink(inode, 2);	/* Use getattr to fix if necessary */
2642 	if (p->iop)
2643 		inode->i_op = p->iop;
2644 	if (p->fop)
2645 		inode->i_fop = p->fop;
2646 	ei->op = p->op;
2647 	pid_update_inode(task, inode);
2648 	d_set_d_op(dentry, &pid_dentry_operations);
2649 	return d_splice_alias(inode, dentry);
2650 }
2651 
proc_pident_lookup(struct inode * dir,struct dentry * dentry,const struct pid_entry * p,const struct pid_entry * end)2652 static struct dentry *proc_pident_lookup(struct inode *dir,
2653 					 struct dentry *dentry,
2654 					 const struct pid_entry *p,
2655 					 const struct pid_entry *end)
2656 {
2657 	struct task_struct *task = get_proc_task(dir);
2658 	struct dentry *res = ERR_PTR(-ENOENT);
2659 
2660 	if (!task)
2661 		goto out_no_task;
2662 
2663 	/*
2664 	 * Yes, it does not scale. And it should not. Don't add
2665 	 * new entries into /proc/<tgid>/ without very good reasons.
2666 	 */
2667 	for (; p < end; p++) {
2668 		if (p->len != dentry->d_name.len)
2669 			continue;
2670 		if (!memcmp(dentry->d_name.name, p->name, p->len)) {
2671 			res = proc_pident_instantiate(dentry, task, p);
2672 			break;
2673 		}
2674 	}
2675 	put_task_struct(task);
2676 out_no_task:
2677 	return res;
2678 }
2679 
proc_pident_readdir(struct file * file,struct dir_context * ctx,const struct pid_entry * ents,unsigned int nents)2680 static int proc_pident_readdir(struct file *file, struct dir_context *ctx,
2681 		const struct pid_entry *ents, unsigned int nents)
2682 {
2683 	struct task_struct *task = get_proc_task(file_inode(file));
2684 	const struct pid_entry *p;
2685 
2686 	if (!task)
2687 		return -ENOENT;
2688 
2689 	if (!dir_emit_dots(file, ctx))
2690 		goto out;
2691 
2692 	if (ctx->pos >= nents + 2)
2693 		goto out;
2694 
2695 	for (p = ents + (ctx->pos - 2); p < ents + nents; p++) {
2696 		if (!proc_fill_cache(file, ctx, p->name, p->len,
2697 				proc_pident_instantiate, task, p))
2698 			break;
2699 		ctx->pos++;
2700 	}
2701 out:
2702 	put_task_struct(task);
2703 	return 0;
2704 }
2705 
2706 #ifdef CONFIG_SECURITY
proc_pid_attr_open(struct inode * inode,struct file * file)2707 static int proc_pid_attr_open(struct inode *inode, struct file *file)
2708 {
2709 	file->private_data = NULL;
2710 	__mem_open(inode, file, PTRACE_MODE_READ_FSCREDS);
2711 	return 0;
2712 }
2713 
proc_pid_attr_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)2714 static ssize_t proc_pid_attr_read(struct file * file, char __user * buf,
2715 				  size_t count, loff_t *ppos)
2716 {
2717 	struct inode * inode = file_inode(file);
2718 	char *p = NULL;
2719 	ssize_t length;
2720 	struct task_struct *task = get_proc_task(inode);
2721 
2722 	if (!task)
2723 		return -ESRCH;
2724 
2725 	length = security_getprocattr(task, PROC_I(inode)->op.lsm,
2726 				      (char*)file->f_path.dentry->d_name.name,
2727 				      &p);
2728 	put_task_struct(task);
2729 	if (length > 0)
2730 		length = simple_read_from_buffer(buf, count, ppos, p, length);
2731 	kfree(p);
2732 	return length;
2733 }
2734 
proc_pid_attr_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)2735 static ssize_t proc_pid_attr_write(struct file * file, const char __user * buf,
2736 				   size_t count, loff_t *ppos)
2737 {
2738 	struct inode * inode = file_inode(file);
2739 	struct task_struct *task;
2740 	void *page;
2741 	int rv;
2742 
2743 	/* A task may only write when it was the opener. */
2744 	if (file->private_data != current->mm)
2745 		return -EPERM;
2746 
2747 	rcu_read_lock();
2748 	task = pid_task(proc_pid(inode), PIDTYPE_PID);
2749 	if (!task) {
2750 		rcu_read_unlock();
2751 		return -ESRCH;
2752 	}
2753 	/* A task may only write its own attributes. */
2754 	if (current != task) {
2755 		rcu_read_unlock();
2756 		return -EACCES;
2757 	}
2758 	/* Prevent changes to overridden credentials. */
2759 	if (current_cred() != current_real_cred()) {
2760 		rcu_read_unlock();
2761 		return -EBUSY;
2762 	}
2763 	rcu_read_unlock();
2764 
2765 	if (count > PAGE_SIZE)
2766 		count = PAGE_SIZE;
2767 
2768 	/* No partial writes. */
2769 	if (*ppos != 0)
2770 		return -EINVAL;
2771 
2772 	page = memdup_user(buf, count);
2773 	if (IS_ERR(page)) {
2774 		rv = PTR_ERR(page);
2775 		goto out;
2776 	}
2777 
2778 	/* Guard against adverse ptrace interaction */
2779 	rv = mutex_lock_interruptible(&current->signal->cred_guard_mutex);
2780 	if (rv < 0)
2781 		goto out_free;
2782 
2783 	rv = security_setprocattr(PROC_I(inode)->op.lsm,
2784 				  file->f_path.dentry->d_name.name, page,
2785 				  count);
2786 	mutex_unlock(&current->signal->cred_guard_mutex);
2787 out_free:
2788 	kfree(page);
2789 out:
2790 	return rv;
2791 }
2792 
2793 static const struct file_operations proc_pid_attr_operations = {
2794 	.open		= proc_pid_attr_open,
2795 	.read		= proc_pid_attr_read,
2796 	.write		= proc_pid_attr_write,
2797 	.llseek		= generic_file_llseek,
2798 	.release	= mem_release,
2799 };
2800 
2801 #define LSM_DIR_OPS(LSM) \
2802 static int proc_##LSM##_attr_dir_iterate(struct file *filp, \
2803 			     struct dir_context *ctx) \
2804 { \
2805 	return proc_pident_readdir(filp, ctx, \
2806 				   LSM##_attr_dir_stuff, \
2807 				   ARRAY_SIZE(LSM##_attr_dir_stuff)); \
2808 } \
2809 \
2810 static const struct file_operations proc_##LSM##_attr_dir_ops = { \
2811 	.read		= generic_read_dir, \
2812 	.iterate	= proc_##LSM##_attr_dir_iterate, \
2813 	.llseek		= default_llseek, \
2814 }; \
2815 \
2816 static struct dentry *proc_##LSM##_attr_dir_lookup(struct inode *dir, \
2817 				struct dentry *dentry, unsigned int flags) \
2818 { \
2819 	return proc_pident_lookup(dir, dentry, \
2820 				  LSM##_attr_dir_stuff, \
2821 				  LSM##_attr_dir_stuff + ARRAY_SIZE(LSM##_attr_dir_stuff)); \
2822 } \
2823 \
2824 static const struct inode_operations proc_##LSM##_attr_dir_inode_ops = { \
2825 	.lookup		= proc_##LSM##_attr_dir_lookup, \
2826 	.getattr	= pid_getattr, \
2827 	.setattr	= proc_setattr, \
2828 }
2829 
2830 #ifdef CONFIG_SECURITY_SMACK
2831 static const struct pid_entry smack_attr_dir_stuff[] = {
2832 	ATTR("smack", "current",	0666),
2833 };
2834 LSM_DIR_OPS(smack);
2835 #endif
2836 
2837 #ifdef CONFIG_SECURITY_APPARMOR
2838 static const struct pid_entry apparmor_attr_dir_stuff[] = {
2839 	ATTR("apparmor", "current",	0666),
2840 	ATTR("apparmor", "prev",	0444),
2841 	ATTR("apparmor", "exec",	0666),
2842 };
2843 LSM_DIR_OPS(apparmor);
2844 #endif
2845 
2846 static const struct pid_entry attr_dir_stuff[] = {
2847 	ATTR(NULL, "current",		0666),
2848 	ATTR(NULL, "prev",		0444),
2849 	ATTR(NULL, "exec",		0666),
2850 	ATTR(NULL, "fscreate",		0666),
2851 	ATTR(NULL, "keycreate",		0666),
2852 	ATTR(NULL, "sockcreate",	0666),
2853 #ifdef CONFIG_SECURITY_SMACK
2854 	DIR("smack",			0555,
2855 	    proc_smack_attr_dir_inode_ops, proc_smack_attr_dir_ops),
2856 #endif
2857 #ifdef CONFIG_SECURITY_APPARMOR
2858 	DIR("apparmor",			0555,
2859 	    proc_apparmor_attr_dir_inode_ops, proc_apparmor_attr_dir_ops),
2860 #endif
2861 };
2862 
proc_attr_dir_readdir(struct file * file,struct dir_context * ctx)2863 static int proc_attr_dir_readdir(struct file *file, struct dir_context *ctx)
2864 {
2865 	return proc_pident_readdir(file, ctx,
2866 				   attr_dir_stuff, ARRAY_SIZE(attr_dir_stuff));
2867 }
2868 
2869 static const struct file_operations proc_attr_dir_operations = {
2870 	.read		= generic_read_dir,
2871 	.iterate_shared	= proc_attr_dir_readdir,
2872 	.llseek		= generic_file_llseek,
2873 };
2874 
proc_attr_dir_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)2875 static struct dentry *proc_attr_dir_lookup(struct inode *dir,
2876 				struct dentry *dentry, unsigned int flags)
2877 {
2878 	return proc_pident_lookup(dir, dentry,
2879 				  attr_dir_stuff,
2880 				  attr_dir_stuff + ARRAY_SIZE(attr_dir_stuff));
2881 }
2882 
2883 static const struct inode_operations proc_attr_dir_inode_operations = {
2884 	.lookup		= proc_attr_dir_lookup,
2885 	.getattr	= pid_getattr,
2886 	.setattr	= proc_setattr,
2887 };
2888 
2889 #endif
2890 
2891 #ifdef CONFIG_ELF_CORE
proc_coredump_filter_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)2892 static ssize_t proc_coredump_filter_read(struct file *file, char __user *buf,
2893 					 size_t count, loff_t *ppos)
2894 {
2895 	struct task_struct *task = get_proc_task(file_inode(file));
2896 	struct mm_struct *mm;
2897 	char buffer[PROC_NUMBUF];
2898 	size_t len;
2899 	int ret;
2900 
2901 	if (!task)
2902 		return -ESRCH;
2903 
2904 	ret = 0;
2905 	mm = get_task_mm(task);
2906 	if (mm) {
2907 		len = snprintf(buffer, sizeof(buffer), "%08lx\n",
2908 			       ((mm->flags & MMF_DUMP_FILTER_MASK) >>
2909 				MMF_DUMP_FILTER_SHIFT));
2910 		mmput(mm);
2911 		ret = simple_read_from_buffer(buf, count, ppos, buffer, len);
2912 	}
2913 
2914 	put_task_struct(task);
2915 
2916 	return ret;
2917 }
2918 
proc_coredump_filter_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)2919 static ssize_t proc_coredump_filter_write(struct file *file,
2920 					  const char __user *buf,
2921 					  size_t count,
2922 					  loff_t *ppos)
2923 {
2924 	struct task_struct *task;
2925 	struct mm_struct *mm;
2926 	unsigned int val;
2927 	int ret;
2928 	int i;
2929 	unsigned long mask;
2930 
2931 	ret = kstrtouint_from_user(buf, count, 0, &val);
2932 	if (ret < 0)
2933 		return ret;
2934 
2935 	ret = -ESRCH;
2936 	task = get_proc_task(file_inode(file));
2937 	if (!task)
2938 		goto out_no_task;
2939 
2940 	mm = get_task_mm(task);
2941 	if (!mm)
2942 		goto out_no_mm;
2943 	ret = 0;
2944 
2945 	for (i = 0, mask = 1; i < MMF_DUMP_FILTER_BITS; i++, mask <<= 1) {
2946 		if (val & mask)
2947 			set_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
2948 		else
2949 			clear_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
2950 	}
2951 
2952 	mmput(mm);
2953  out_no_mm:
2954 	put_task_struct(task);
2955  out_no_task:
2956 	if (ret < 0)
2957 		return ret;
2958 	return count;
2959 }
2960 
2961 static const struct file_operations proc_coredump_filter_operations = {
2962 	.read		= proc_coredump_filter_read,
2963 	.write		= proc_coredump_filter_write,
2964 	.llseek		= generic_file_llseek,
2965 };
2966 #endif
2967 
2968 #ifdef CONFIG_TASK_IO_ACCOUNTING
do_io_accounting(struct task_struct * task,struct seq_file * m,int whole)2969 static int do_io_accounting(struct task_struct *task, struct seq_file *m, int whole)
2970 {
2971 	struct task_io_accounting acct = task->ioac;
2972 	unsigned long flags;
2973 	int result;
2974 
2975 	result = down_read_killable(&task->signal->exec_update_lock);
2976 	if (result)
2977 		return result;
2978 
2979 	if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS)) {
2980 		result = -EACCES;
2981 		goto out_unlock;
2982 	}
2983 
2984 	if (whole && lock_task_sighand(task, &flags)) {
2985 		struct task_struct *t = task;
2986 
2987 		task_io_accounting_add(&acct, &task->signal->ioac);
2988 		while_each_thread(task, t)
2989 			task_io_accounting_add(&acct, &t->ioac);
2990 
2991 		unlock_task_sighand(task, &flags);
2992 	}
2993 	seq_printf(m,
2994 		   "rchar: %llu\n"
2995 		   "wchar: %llu\n"
2996 		   "syscr: %llu\n"
2997 		   "syscw: %llu\n"
2998 		   "read_bytes: %llu\n"
2999 		   "write_bytes: %llu\n"
3000 		   "cancelled_write_bytes: %llu\n",
3001 		   (unsigned long long)acct.rchar,
3002 		   (unsigned long long)acct.wchar,
3003 		   (unsigned long long)acct.syscr,
3004 		   (unsigned long long)acct.syscw,
3005 		   (unsigned long long)acct.read_bytes,
3006 		   (unsigned long long)acct.write_bytes,
3007 		   (unsigned long long)acct.cancelled_write_bytes);
3008 	result = 0;
3009 
3010 out_unlock:
3011 	up_read(&task->signal->exec_update_lock);
3012 	return result;
3013 }
3014 
proc_tid_io_accounting(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)3015 static int proc_tid_io_accounting(struct seq_file *m, struct pid_namespace *ns,
3016 				  struct pid *pid, struct task_struct *task)
3017 {
3018 	return do_io_accounting(task, m, 0);
3019 }
3020 
proc_tgid_io_accounting(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)3021 static int proc_tgid_io_accounting(struct seq_file *m, struct pid_namespace *ns,
3022 				   struct pid *pid, struct task_struct *task)
3023 {
3024 	return do_io_accounting(task, m, 1);
3025 }
3026 #endif /* CONFIG_TASK_IO_ACCOUNTING */
3027 
3028 #ifdef CONFIG_USER_NS
proc_id_map_open(struct inode * inode,struct file * file,const struct seq_operations * seq_ops)3029 static int proc_id_map_open(struct inode *inode, struct file *file,
3030 	const struct seq_operations *seq_ops)
3031 {
3032 	struct user_namespace *ns = NULL;
3033 	struct task_struct *task;
3034 	struct seq_file *seq;
3035 	int ret = -EINVAL;
3036 
3037 	task = get_proc_task(inode);
3038 	if (task) {
3039 		rcu_read_lock();
3040 		ns = get_user_ns(task_cred_xxx(task, user_ns));
3041 		rcu_read_unlock();
3042 		put_task_struct(task);
3043 	}
3044 	if (!ns)
3045 		goto err;
3046 
3047 	ret = seq_open(file, seq_ops);
3048 	if (ret)
3049 		goto err_put_ns;
3050 
3051 	seq = file->private_data;
3052 	seq->private = ns;
3053 
3054 	return 0;
3055 err_put_ns:
3056 	put_user_ns(ns);
3057 err:
3058 	return ret;
3059 }
3060 
proc_id_map_release(struct inode * inode,struct file * file)3061 static int proc_id_map_release(struct inode *inode, struct file *file)
3062 {
3063 	struct seq_file *seq = file->private_data;
3064 	struct user_namespace *ns = seq->private;
3065 	put_user_ns(ns);
3066 	return seq_release(inode, file);
3067 }
3068 
proc_uid_map_open(struct inode * inode,struct file * file)3069 static int proc_uid_map_open(struct inode *inode, struct file *file)
3070 {
3071 	return proc_id_map_open(inode, file, &proc_uid_seq_operations);
3072 }
3073 
proc_gid_map_open(struct inode * inode,struct file * file)3074 static int proc_gid_map_open(struct inode *inode, struct file *file)
3075 {
3076 	return proc_id_map_open(inode, file, &proc_gid_seq_operations);
3077 }
3078 
proc_projid_map_open(struct inode * inode,struct file * file)3079 static int proc_projid_map_open(struct inode *inode, struct file *file)
3080 {
3081 	return proc_id_map_open(inode, file, &proc_projid_seq_operations);
3082 }
3083 
3084 static const struct file_operations proc_uid_map_operations = {
3085 	.open		= proc_uid_map_open,
3086 	.write		= proc_uid_map_write,
3087 	.read		= seq_read,
3088 	.llseek		= seq_lseek,
3089 	.release	= proc_id_map_release,
3090 };
3091 
3092 static const struct file_operations proc_gid_map_operations = {
3093 	.open		= proc_gid_map_open,
3094 	.write		= proc_gid_map_write,
3095 	.read		= seq_read,
3096 	.llseek		= seq_lseek,
3097 	.release	= proc_id_map_release,
3098 };
3099 
3100 static const struct file_operations proc_projid_map_operations = {
3101 	.open		= proc_projid_map_open,
3102 	.write		= proc_projid_map_write,
3103 	.read		= seq_read,
3104 	.llseek		= seq_lseek,
3105 	.release	= proc_id_map_release,
3106 };
3107 
proc_setgroups_open(struct inode * inode,struct file * file)3108 static int proc_setgroups_open(struct inode *inode, struct file *file)
3109 {
3110 	struct user_namespace *ns = NULL;
3111 	struct task_struct *task;
3112 	int ret;
3113 
3114 	ret = -ESRCH;
3115 	task = get_proc_task(inode);
3116 	if (task) {
3117 		rcu_read_lock();
3118 		ns = get_user_ns(task_cred_xxx(task, user_ns));
3119 		rcu_read_unlock();
3120 		put_task_struct(task);
3121 	}
3122 	if (!ns)
3123 		goto err;
3124 
3125 	if (file->f_mode & FMODE_WRITE) {
3126 		ret = -EACCES;
3127 		if (!ns_capable(ns, CAP_SYS_ADMIN))
3128 			goto err_put_ns;
3129 	}
3130 
3131 	ret = single_open(file, &proc_setgroups_show, ns);
3132 	if (ret)
3133 		goto err_put_ns;
3134 
3135 	return 0;
3136 err_put_ns:
3137 	put_user_ns(ns);
3138 err:
3139 	return ret;
3140 }
3141 
proc_setgroups_release(struct inode * inode,struct file * file)3142 static int proc_setgroups_release(struct inode *inode, struct file *file)
3143 {
3144 	struct seq_file *seq = file->private_data;
3145 	struct user_namespace *ns = seq->private;
3146 	int ret = single_release(inode, file);
3147 	put_user_ns(ns);
3148 	return ret;
3149 }
3150 
3151 static const struct file_operations proc_setgroups_operations = {
3152 	.open		= proc_setgroups_open,
3153 	.write		= proc_setgroups_write,
3154 	.read		= seq_read,
3155 	.llseek		= seq_lseek,
3156 	.release	= proc_setgroups_release,
3157 };
3158 #endif /* CONFIG_USER_NS */
3159 
proc_pid_personality(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)3160 static int proc_pid_personality(struct seq_file *m, struct pid_namespace *ns,
3161 				struct pid *pid, struct task_struct *task)
3162 {
3163 	int err = lock_trace(task);
3164 	if (!err) {
3165 		seq_printf(m, "%08x\n", task->personality);
3166 		unlock_trace(task);
3167 	}
3168 	return err;
3169 }
3170 
3171 #ifdef CONFIG_LIVEPATCH
proc_pid_patch_state(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)3172 static int proc_pid_patch_state(struct seq_file *m, struct pid_namespace *ns,
3173 				struct pid *pid, struct task_struct *task)
3174 {
3175 	seq_printf(m, "%d\n", task->patch_state);
3176 	return 0;
3177 }
3178 #endif /* CONFIG_LIVEPATCH */
3179 
3180 #ifdef CONFIG_STACKLEAK_METRICS
proc_stack_depth(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)3181 static int proc_stack_depth(struct seq_file *m, struct pid_namespace *ns,
3182 				struct pid *pid, struct task_struct *task)
3183 {
3184 	unsigned long prev_depth = THREAD_SIZE -
3185 				(task->prev_lowest_stack & (THREAD_SIZE - 1));
3186 	unsigned long depth = THREAD_SIZE -
3187 				(task->lowest_stack & (THREAD_SIZE - 1));
3188 
3189 	seq_printf(m, "previous stack depth: %lu\nstack depth: %lu\n",
3190 							prev_depth, depth);
3191 	return 0;
3192 }
3193 #endif /* CONFIG_STACKLEAK_METRICS */
3194 
3195 /*
3196  * Thread groups
3197  */
3198 static const struct file_operations proc_task_operations;
3199 static const struct inode_operations proc_task_inode_operations;
3200 
3201 static const struct pid_entry tgid_base_stuff[] = {
3202 	DIR("task",       S_IRUGO|S_IXUGO, proc_task_inode_operations, proc_task_operations),
3203 	DIR("fd",         S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
3204 	DIR("map_files",  S_IRUSR|S_IXUSR, proc_map_files_inode_operations, proc_map_files_operations),
3205 	DIR("fdinfo",     S_IRUGO|S_IXUGO, proc_fdinfo_inode_operations, proc_fdinfo_operations),
3206 	DIR("ns",	  S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
3207 #ifdef CONFIG_NET
3208 	DIR("net",        S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
3209 #endif
3210 	REG("environ",    S_IRUSR, proc_environ_operations),
3211 	REG("auxv",       S_IRUSR, proc_auxv_operations),
3212 	ONE("status",     S_IRUGO, proc_pid_status),
3213 	ONE("personality", S_IRUSR, proc_pid_personality),
3214 	ONE("limits",	  S_IRUGO, proc_pid_limits),
3215 #ifdef CONFIG_SCHED_DEBUG
3216 	REG("sched",      S_IRUGO|S_IWUSR, proc_pid_sched_operations),
3217 #endif
3218 #ifdef CONFIG_SCHED_AUTOGROUP
3219 	REG("autogroup",  S_IRUGO|S_IWUSR, proc_pid_sched_autogroup_operations),
3220 #endif
3221 #ifdef CONFIG_TIME_NS
3222 	REG("timens_offsets",  S_IRUGO|S_IWUSR, proc_timens_offsets_operations),
3223 #endif
3224 	REG("comm",      S_IRUGO|S_IWUSR, proc_pid_set_comm_operations),
3225 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
3226 	ONE("syscall",    S_IRUSR, proc_pid_syscall),
3227 #endif
3228 	REG("cmdline",    S_IRUGO, proc_pid_cmdline_ops),
3229 	ONE("stat",       S_IRUGO, proc_tgid_stat),
3230 	ONE("statm",      S_IRUGO, proc_pid_statm),
3231 	REG("maps",       S_IRUGO, proc_pid_maps_operations),
3232 #ifdef CONFIG_NUMA
3233 	REG("numa_maps",  S_IRUGO, proc_pid_numa_maps_operations),
3234 #endif
3235 	REG("mem",        S_IRUSR|S_IWUSR, proc_mem_operations),
3236 	LNK("cwd",        proc_cwd_link),
3237 	LNK("root",       proc_root_link),
3238 	LNK("exe",        proc_exe_link),
3239 	REG("mounts",     S_IRUGO, proc_mounts_operations),
3240 	REG("mountinfo",  S_IRUGO, proc_mountinfo_operations),
3241 	REG("mountstats", S_IRUSR, proc_mountstats_operations),
3242 #ifdef CONFIG_PROC_PAGE_MONITOR
3243 	REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
3244 	REG("smaps",      S_IRUGO, proc_pid_smaps_operations),
3245 	REG("smaps_rollup", S_IRUGO, proc_pid_smaps_rollup_operations),
3246 	REG("pagemap",    S_IRUSR, proc_pagemap_operations),
3247 #endif
3248 #ifdef CONFIG_SECURITY
3249 	DIR("attr",       S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
3250 #endif
3251 #ifdef CONFIG_KALLSYMS
3252 	ONE("wchan",      S_IRUGO, proc_pid_wchan),
3253 #endif
3254 #ifdef CONFIG_STACKTRACE
3255 	ONE("stack",      S_IRUSR, proc_pid_stack),
3256 #endif
3257 #ifdef CONFIG_SCHED_INFO
3258 	ONE("schedstat",  S_IRUGO, proc_pid_schedstat),
3259 #endif
3260 #ifdef CONFIG_LATENCYTOP
3261 	REG("latency",  S_IRUGO, proc_lstats_operations),
3262 #endif
3263 #ifdef CONFIG_PROC_PID_CPUSET
3264 	ONE("cpuset",     S_IRUGO, proc_cpuset_show),
3265 #endif
3266 #ifdef CONFIG_CGROUPS
3267 	ONE("cgroup",  S_IRUGO, proc_cgroup_show),
3268 #endif
3269 #ifdef CONFIG_PROC_CPU_RESCTRL
3270 	ONE("cpu_resctrl_groups", S_IRUGO, proc_resctrl_show),
3271 #endif
3272 	ONE("oom_score",  S_IRUGO, proc_oom_score),
3273 	REG("oom_adj",    S_IRUGO|S_IWUSR, proc_oom_adj_operations),
3274 	REG("oom_score_adj", S_IRUGO|S_IWUSR, proc_oom_score_adj_operations),
3275 #ifdef CONFIG_AUDIT
3276 	REG("loginuid",   S_IWUSR|S_IRUGO, proc_loginuid_operations),
3277 	REG("sessionid",  S_IRUGO, proc_sessionid_operations),
3278 #endif
3279 #ifdef CONFIG_FAULT_INJECTION
3280 	REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
3281 	REG("fail-nth", 0644, proc_fail_nth_operations),
3282 #endif
3283 #ifdef CONFIG_ELF_CORE
3284 	REG("coredump_filter", S_IRUGO|S_IWUSR, proc_coredump_filter_operations),
3285 #endif
3286 #ifdef CONFIG_TASK_IO_ACCOUNTING
3287 	ONE("io",	S_IRUSR, proc_tgid_io_accounting),
3288 #endif
3289 #ifdef CONFIG_USER_NS
3290 	REG("uid_map",    S_IRUGO|S_IWUSR, proc_uid_map_operations),
3291 	REG("gid_map",    S_IRUGO|S_IWUSR, proc_gid_map_operations),
3292 	REG("projid_map", S_IRUGO|S_IWUSR, proc_projid_map_operations),
3293 	REG("setgroups",  S_IRUGO|S_IWUSR, proc_setgroups_operations),
3294 #endif
3295 #if defined(CONFIG_CHECKPOINT_RESTORE) && defined(CONFIG_POSIX_TIMERS)
3296 	REG("timers",	  S_IRUGO, proc_timers_operations),
3297 #endif
3298 	REG("timerslack_ns", S_IRUGO|S_IWUGO, proc_pid_set_timerslack_ns_operations),
3299 #ifdef CONFIG_LIVEPATCH
3300 	ONE("patch_state",  S_IRUSR, proc_pid_patch_state),
3301 #endif
3302 #ifdef CONFIG_CPU_FREQ_TIMES
3303 	ONE("time_in_state", 0444, proc_time_in_state_show),
3304 #endif
3305 #ifdef CONFIG_STACKLEAK_METRICS
3306 	ONE("stack_depth", S_IRUGO, proc_stack_depth),
3307 #endif
3308 #ifdef CONFIG_PROC_PID_ARCH_STATUS
3309 	ONE("arch_status", S_IRUGO, proc_pid_arch_status),
3310 #endif
3311 };
3312 
proc_tgid_base_readdir(struct file * file,struct dir_context * ctx)3313 static int proc_tgid_base_readdir(struct file *file, struct dir_context *ctx)
3314 {
3315 	return proc_pident_readdir(file, ctx,
3316 				   tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff));
3317 }
3318 
3319 static const struct file_operations proc_tgid_base_operations = {
3320 	.read		= generic_read_dir,
3321 	.iterate_shared	= proc_tgid_base_readdir,
3322 	.llseek		= generic_file_llseek,
3323 };
3324 
tgid_pidfd_to_pid(const struct file * file)3325 struct pid *tgid_pidfd_to_pid(const struct file *file)
3326 {
3327 	if (file->f_op != &proc_tgid_base_operations)
3328 		return ERR_PTR(-EBADF);
3329 
3330 	return proc_pid(file_inode(file));
3331 }
3332 
proc_tgid_base_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)3333 static struct dentry *proc_tgid_base_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
3334 {
3335 	return proc_pident_lookup(dir, dentry,
3336 				  tgid_base_stuff,
3337 				  tgid_base_stuff + ARRAY_SIZE(tgid_base_stuff));
3338 }
3339 
3340 static const struct inode_operations proc_tgid_base_inode_operations = {
3341 	.lookup		= proc_tgid_base_lookup,
3342 	.getattr	= pid_getattr,
3343 	.setattr	= proc_setattr,
3344 	.permission	= proc_pid_permission,
3345 };
3346 
3347 /**
3348  * proc_flush_pid -  Remove dcache entries for @pid from the /proc dcache.
3349  * @pid: pid that should be flushed.
3350  *
3351  * This function walks a list of inodes (that belong to any proc
3352  * filesystem) that are attached to the pid and flushes them from
3353  * the dentry cache.
3354  *
3355  * It is safe and reasonable to cache /proc entries for a task until
3356  * that task exits.  After that they just clog up the dcache with
3357  * useless entries, possibly causing useful dcache entries to be
3358  * flushed instead.  This routine is provided to flush those useless
3359  * dcache entries when a process is reaped.
3360  *
3361  * NOTE: This routine is just an optimization so it does not guarantee
3362  *       that no dcache entries will exist after a process is reaped
3363  *       it just makes it very unlikely that any will persist.
3364  */
3365 
proc_flush_pid(struct pid * pid)3366 void proc_flush_pid(struct pid *pid)
3367 {
3368 	proc_invalidate_siblings_dcache(&pid->inodes, &pid->lock);
3369 }
3370 
proc_pid_instantiate(struct dentry * dentry,struct task_struct * task,const void * ptr)3371 static struct dentry *proc_pid_instantiate(struct dentry * dentry,
3372 				   struct task_struct *task, const void *ptr)
3373 {
3374 	struct inode *inode;
3375 
3376 	inode = proc_pid_make_base_inode(dentry->d_sb, task,
3377 					 S_IFDIR | S_IRUGO | S_IXUGO);
3378 	if (!inode)
3379 		return ERR_PTR(-ENOENT);
3380 
3381 	inode->i_op = &proc_tgid_base_inode_operations;
3382 	inode->i_fop = &proc_tgid_base_operations;
3383 	inode->i_flags|=S_IMMUTABLE;
3384 
3385 	set_nlink(inode, nlink_tgid);
3386 	pid_update_inode(task, inode);
3387 
3388 	d_set_d_op(dentry, &pid_dentry_operations);
3389 	return d_splice_alias(inode, dentry);
3390 }
3391 
proc_pid_lookup(struct dentry * dentry,unsigned int flags)3392 struct dentry *proc_pid_lookup(struct dentry *dentry, unsigned int flags)
3393 {
3394 	struct task_struct *task;
3395 	unsigned tgid;
3396 	struct proc_fs_info *fs_info;
3397 	struct pid_namespace *ns;
3398 	struct dentry *result = ERR_PTR(-ENOENT);
3399 
3400 	tgid = name_to_int(&dentry->d_name);
3401 	if (tgid == ~0U)
3402 		goto out;
3403 
3404 	fs_info = proc_sb_info(dentry->d_sb);
3405 	ns = fs_info->pid_ns;
3406 	rcu_read_lock();
3407 	task = find_task_by_pid_ns(tgid, ns);
3408 	if (task)
3409 		get_task_struct(task);
3410 	rcu_read_unlock();
3411 	if (!task)
3412 		goto out;
3413 
3414 	/* Limit procfs to only ptraceable tasks */
3415 	if (fs_info->hide_pid == HIDEPID_NOT_PTRACEABLE) {
3416 		if (!has_pid_permissions(fs_info, task, HIDEPID_NO_ACCESS))
3417 			goto out_put_task;
3418 	}
3419 
3420 	result = proc_pid_instantiate(dentry, task, NULL);
3421 out_put_task:
3422 	put_task_struct(task);
3423 out:
3424 	return result;
3425 }
3426 
3427 /*
3428  * Find the first task with tgid >= tgid
3429  *
3430  */
3431 struct tgid_iter {
3432 	unsigned int tgid;
3433 	struct task_struct *task;
3434 };
next_tgid(struct pid_namespace * ns,struct tgid_iter iter)3435 static struct tgid_iter next_tgid(struct pid_namespace *ns, struct tgid_iter iter)
3436 {
3437 	struct pid *pid;
3438 
3439 	if (iter.task)
3440 		put_task_struct(iter.task);
3441 	rcu_read_lock();
3442 retry:
3443 	iter.task = NULL;
3444 	pid = find_ge_pid(iter.tgid, ns);
3445 	if (pid) {
3446 		iter.tgid = pid_nr_ns(pid, ns);
3447 		iter.task = pid_task(pid, PIDTYPE_TGID);
3448 		if (!iter.task) {
3449 			iter.tgid += 1;
3450 			goto retry;
3451 		}
3452 		get_task_struct(iter.task);
3453 	}
3454 	rcu_read_unlock();
3455 	return iter;
3456 }
3457 
3458 #define TGID_OFFSET (FIRST_PROCESS_ENTRY + 2)
3459 
3460 /* for the /proc/ directory itself, after non-process stuff has been done */
proc_pid_readdir(struct file * file,struct dir_context * ctx)3461 int proc_pid_readdir(struct file *file, struct dir_context *ctx)
3462 {
3463 	struct tgid_iter iter;
3464 	struct proc_fs_info *fs_info = proc_sb_info(file_inode(file)->i_sb);
3465 	struct pid_namespace *ns = proc_pid_ns(file_inode(file)->i_sb);
3466 	loff_t pos = ctx->pos;
3467 
3468 	if (pos >= PID_MAX_LIMIT + TGID_OFFSET)
3469 		return 0;
3470 
3471 	if (pos == TGID_OFFSET - 2) {
3472 		struct inode *inode = d_inode(fs_info->proc_self);
3473 		if (!dir_emit(ctx, "self", 4, inode->i_ino, DT_LNK))
3474 			return 0;
3475 		ctx->pos = pos = pos + 1;
3476 	}
3477 	if (pos == TGID_OFFSET - 1) {
3478 		struct inode *inode = d_inode(fs_info->proc_thread_self);
3479 		if (!dir_emit(ctx, "thread-self", 11, inode->i_ino, DT_LNK))
3480 			return 0;
3481 		ctx->pos = pos = pos + 1;
3482 	}
3483 	iter.tgid = pos - TGID_OFFSET;
3484 	iter.task = NULL;
3485 	for (iter = next_tgid(ns, iter);
3486 	     iter.task;
3487 	     iter.tgid += 1, iter = next_tgid(ns, iter)) {
3488 		char name[10 + 1];
3489 		unsigned int len;
3490 
3491 		cond_resched();
3492 		if (!has_pid_permissions(fs_info, iter.task, HIDEPID_INVISIBLE))
3493 			continue;
3494 
3495 		len = snprintf(name, sizeof(name), "%u", iter.tgid);
3496 		ctx->pos = iter.tgid + TGID_OFFSET;
3497 		if (!proc_fill_cache(file, ctx, name, len,
3498 				     proc_pid_instantiate, iter.task, NULL)) {
3499 			put_task_struct(iter.task);
3500 			return 0;
3501 		}
3502 	}
3503 	ctx->pos = PID_MAX_LIMIT + TGID_OFFSET;
3504 	return 0;
3505 }
3506 
3507 /*
3508  * proc_tid_comm_permission is a special permission function exclusively
3509  * used for the node /proc/<pid>/task/<tid>/comm.
3510  * It bypasses generic permission checks in the case where a task of the same
3511  * task group attempts to access the node.
3512  * The rationale behind this is that glibc and bionic access this node for
3513  * cross thread naming (pthread_set/getname_np(!self)). However, if
3514  * PR_SET_DUMPABLE gets set to 0 this node among others becomes uid=0 gid=0,
3515  * which locks out the cross thread naming implementation.
3516  * This function makes sure that the node is always accessible for members of
3517  * same thread group.
3518  */
proc_tid_comm_permission(struct inode * inode,int mask)3519 static int proc_tid_comm_permission(struct inode *inode, int mask)
3520 {
3521 	bool is_same_tgroup;
3522 	struct task_struct *task;
3523 
3524 	task = get_proc_task(inode);
3525 	if (!task)
3526 		return -ESRCH;
3527 	is_same_tgroup = same_thread_group(current, task);
3528 	put_task_struct(task);
3529 
3530 	if (likely(is_same_tgroup && !(mask & MAY_EXEC))) {
3531 		/* This file (/proc/<pid>/task/<tid>/comm) can always be
3532 		 * read or written by the members of the corresponding
3533 		 * thread group.
3534 		 */
3535 		return 0;
3536 	}
3537 
3538 	return generic_permission(inode, mask);
3539 }
3540 
3541 static const struct inode_operations proc_tid_comm_inode_operations = {
3542 		.setattr	= proc_setattr,
3543 		.permission	= proc_tid_comm_permission,
3544 };
3545 
3546 /*
3547  * Tasks
3548  */
3549 static const struct pid_entry tid_base_stuff[] = {
3550 	DIR("fd",        S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
3551 	DIR("fdinfo",    S_IRUGO|S_IXUGO, proc_fdinfo_inode_operations, proc_fdinfo_operations),
3552 	DIR("ns",	 S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
3553 #ifdef CONFIG_NET
3554 	DIR("net",        S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
3555 #endif
3556 	REG("environ",   S_IRUSR, proc_environ_operations),
3557 	REG("auxv",      S_IRUSR, proc_auxv_operations),
3558 	ONE("status",    S_IRUGO, proc_pid_status),
3559 	ONE("personality", S_IRUSR, proc_pid_personality),
3560 	ONE("limits",	 S_IRUGO, proc_pid_limits),
3561 #ifdef CONFIG_SCHED_DEBUG
3562 	REG("sched",     S_IRUGO|S_IWUSR, proc_pid_sched_operations),
3563 #endif
3564 	NOD("comm",      S_IFREG|S_IRUGO|S_IWUSR,
3565 			 &proc_tid_comm_inode_operations,
3566 			 &proc_pid_set_comm_operations, {}),
3567 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
3568 	ONE("syscall",   S_IRUSR, proc_pid_syscall),
3569 #endif
3570 	REG("cmdline",   S_IRUGO, proc_pid_cmdline_ops),
3571 	ONE("stat",      S_IRUGO, proc_tid_stat),
3572 	ONE("statm",     S_IRUGO, proc_pid_statm),
3573 	REG("maps",      S_IRUGO, proc_pid_maps_operations),
3574 #ifdef CONFIG_PROC_CHILDREN
3575 	REG("children",  S_IRUGO, proc_tid_children_operations),
3576 #endif
3577 #ifdef CONFIG_NUMA
3578 	REG("numa_maps", S_IRUGO, proc_pid_numa_maps_operations),
3579 #endif
3580 	REG("mem",       S_IRUSR|S_IWUSR, proc_mem_operations),
3581 	LNK("cwd",       proc_cwd_link),
3582 	LNK("root",      proc_root_link),
3583 	LNK("exe",       proc_exe_link),
3584 	REG("mounts",    S_IRUGO, proc_mounts_operations),
3585 	REG("mountinfo",  S_IRUGO, proc_mountinfo_operations),
3586 #ifdef CONFIG_PROC_PAGE_MONITOR
3587 	REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
3588 	REG("smaps",     S_IRUGO, proc_pid_smaps_operations),
3589 	REG("smaps_rollup", S_IRUGO, proc_pid_smaps_rollup_operations),
3590 	REG("pagemap",    S_IRUSR, proc_pagemap_operations),
3591 #endif
3592 #ifdef CONFIG_SECURITY
3593 	DIR("attr",      S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
3594 #endif
3595 #ifdef CONFIG_KALLSYMS
3596 	ONE("wchan",     S_IRUGO, proc_pid_wchan),
3597 #endif
3598 #ifdef CONFIG_STACKTRACE
3599 	ONE("stack",      S_IRUSR, proc_pid_stack),
3600 #endif
3601 #ifdef CONFIG_SCHED_INFO
3602 	ONE("schedstat", S_IRUGO, proc_pid_schedstat),
3603 #endif
3604 #ifdef CONFIG_LATENCYTOP
3605 	REG("latency",  S_IRUGO, proc_lstats_operations),
3606 #endif
3607 #ifdef CONFIG_PROC_PID_CPUSET
3608 	ONE("cpuset",    S_IRUGO, proc_cpuset_show),
3609 #endif
3610 #ifdef CONFIG_CGROUPS
3611 	ONE("cgroup",  S_IRUGO, proc_cgroup_show),
3612 #endif
3613 #ifdef CONFIG_PROC_CPU_RESCTRL
3614 	ONE("cpu_resctrl_groups", S_IRUGO, proc_resctrl_show),
3615 #endif
3616 	ONE("oom_score", S_IRUGO, proc_oom_score),
3617 	REG("oom_adj",   S_IRUGO|S_IWUSR, proc_oom_adj_operations),
3618 	REG("oom_score_adj", S_IRUGO|S_IWUSR, proc_oom_score_adj_operations),
3619 #ifdef CONFIG_AUDIT
3620 	REG("loginuid",  S_IWUSR|S_IRUGO, proc_loginuid_operations),
3621 	REG("sessionid",  S_IRUGO, proc_sessionid_operations),
3622 #endif
3623 #ifdef CONFIG_FAULT_INJECTION
3624 	REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
3625 	REG("fail-nth", 0644, proc_fail_nth_operations),
3626 #endif
3627 #ifdef CONFIG_TASK_IO_ACCOUNTING
3628 	ONE("io",	S_IRUSR, proc_tid_io_accounting),
3629 #endif
3630 #ifdef CONFIG_USER_NS
3631 	REG("uid_map",    S_IRUGO|S_IWUSR, proc_uid_map_operations),
3632 	REG("gid_map",    S_IRUGO|S_IWUSR, proc_gid_map_operations),
3633 	REG("projid_map", S_IRUGO|S_IWUSR, proc_projid_map_operations),
3634 	REG("setgroups",  S_IRUGO|S_IWUSR, proc_setgroups_operations),
3635 #endif
3636 #ifdef CONFIG_LIVEPATCH
3637 	ONE("patch_state",  S_IRUSR, proc_pid_patch_state),
3638 #endif
3639 #ifdef CONFIG_PROC_PID_ARCH_STATUS
3640 	ONE("arch_status", S_IRUGO, proc_pid_arch_status),
3641 #endif
3642 #ifdef CONFIG_CPU_FREQ_TIMES
3643 	ONE("time_in_state", 0444, proc_time_in_state_show),
3644 #endif
3645 };
3646 
proc_tid_base_readdir(struct file * file,struct dir_context * ctx)3647 static int proc_tid_base_readdir(struct file *file, struct dir_context *ctx)
3648 {
3649 	return proc_pident_readdir(file, ctx,
3650 				   tid_base_stuff, ARRAY_SIZE(tid_base_stuff));
3651 }
3652 
proc_tid_base_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)3653 static struct dentry *proc_tid_base_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
3654 {
3655 	return proc_pident_lookup(dir, dentry,
3656 				  tid_base_stuff,
3657 				  tid_base_stuff + ARRAY_SIZE(tid_base_stuff));
3658 }
3659 
3660 static const struct file_operations proc_tid_base_operations = {
3661 	.read		= generic_read_dir,
3662 	.iterate_shared	= proc_tid_base_readdir,
3663 	.llseek		= generic_file_llseek,
3664 };
3665 
3666 static const struct inode_operations proc_tid_base_inode_operations = {
3667 	.lookup		= proc_tid_base_lookup,
3668 	.getattr	= pid_getattr,
3669 	.setattr	= proc_setattr,
3670 };
3671 
proc_task_instantiate(struct dentry * dentry,struct task_struct * task,const void * ptr)3672 static struct dentry *proc_task_instantiate(struct dentry *dentry,
3673 	struct task_struct *task, const void *ptr)
3674 {
3675 	struct inode *inode;
3676 	inode = proc_pid_make_base_inode(dentry->d_sb, task,
3677 					 S_IFDIR | S_IRUGO | S_IXUGO);
3678 	if (!inode)
3679 		return ERR_PTR(-ENOENT);
3680 
3681 	inode->i_op = &proc_tid_base_inode_operations;
3682 	inode->i_fop = &proc_tid_base_operations;
3683 	inode->i_flags |= S_IMMUTABLE;
3684 
3685 	set_nlink(inode, nlink_tid);
3686 	pid_update_inode(task, inode);
3687 
3688 	d_set_d_op(dentry, &pid_dentry_operations);
3689 	return d_splice_alias(inode, dentry);
3690 }
3691 
proc_task_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)3692 static struct dentry *proc_task_lookup(struct inode *dir, struct dentry * dentry, unsigned int flags)
3693 {
3694 	struct task_struct *task;
3695 	struct task_struct *leader = get_proc_task(dir);
3696 	unsigned tid;
3697 	struct proc_fs_info *fs_info;
3698 	struct pid_namespace *ns;
3699 	struct dentry *result = ERR_PTR(-ENOENT);
3700 
3701 	if (!leader)
3702 		goto out_no_task;
3703 
3704 	tid = name_to_int(&dentry->d_name);
3705 	if (tid == ~0U)
3706 		goto out;
3707 
3708 	fs_info = proc_sb_info(dentry->d_sb);
3709 	ns = fs_info->pid_ns;
3710 	rcu_read_lock();
3711 	task = find_task_by_pid_ns(tid, ns);
3712 	if (task)
3713 		get_task_struct(task);
3714 	rcu_read_unlock();
3715 	if (!task)
3716 		goto out;
3717 	if (!same_thread_group(leader, task))
3718 		goto out_drop_task;
3719 
3720 	result = proc_task_instantiate(dentry, task, NULL);
3721 out_drop_task:
3722 	put_task_struct(task);
3723 out:
3724 	put_task_struct(leader);
3725 out_no_task:
3726 	return result;
3727 }
3728 
3729 /*
3730  * Find the first tid of a thread group to return to user space.
3731  *
3732  * Usually this is just the thread group leader, but if the users
3733  * buffer was too small or there was a seek into the middle of the
3734  * directory we have more work todo.
3735  *
3736  * In the case of a short read we start with find_task_by_pid.
3737  *
3738  * In the case of a seek we start with the leader and walk nr
3739  * threads past it.
3740  */
first_tid(struct pid * pid,int tid,loff_t f_pos,struct pid_namespace * ns)3741 static struct task_struct *first_tid(struct pid *pid, int tid, loff_t f_pos,
3742 					struct pid_namespace *ns)
3743 {
3744 	struct task_struct *pos, *task;
3745 	unsigned long nr = f_pos;
3746 
3747 	if (nr != f_pos)	/* 32bit overflow? */
3748 		return NULL;
3749 
3750 	rcu_read_lock();
3751 	task = pid_task(pid, PIDTYPE_PID);
3752 	if (!task)
3753 		goto fail;
3754 
3755 	/* Attempt to start with the tid of a thread */
3756 	if (tid && nr) {
3757 		pos = find_task_by_pid_ns(tid, ns);
3758 		if (pos && same_thread_group(pos, task))
3759 			goto found;
3760 	}
3761 
3762 	/* If nr exceeds the number of threads there is nothing todo */
3763 	if (nr >= get_nr_threads(task))
3764 		goto fail;
3765 
3766 	/* If we haven't found our starting place yet start
3767 	 * with the leader and walk nr threads forward.
3768 	 */
3769 	pos = task = task->group_leader;
3770 	do {
3771 		if (!nr--)
3772 			goto found;
3773 	} while_each_thread(task, pos);
3774 fail:
3775 	pos = NULL;
3776 	goto out;
3777 found:
3778 	get_task_struct(pos);
3779 out:
3780 	rcu_read_unlock();
3781 	return pos;
3782 }
3783 
3784 /*
3785  * Find the next thread in the thread list.
3786  * Return NULL if there is an error or no next thread.
3787  *
3788  * The reference to the input task_struct is released.
3789  */
next_tid(struct task_struct * start)3790 static struct task_struct *next_tid(struct task_struct *start)
3791 {
3792 	struct task_struct *pos = NULL;
3793 	rcu_read_lock();
3794 	if (pid_alive(start)) {
3795 		pos = next_thread(start);
3796 		if (thread_group_leader(pos))
3797 			pos = NULL;
3798 		else
3799 			get_task_struct(pos);
3800 	}
3801 	rcu_read_unlock();
3802 	put_task_struct(start);
3803 	return pos;
3804 }
3805 
3806 /* for the /proc/TGID/task/ directories */
proc_task_readdir(struct file * file,struct dir_context * ctx)3807 static int proc_task_readdir(struct file *file, struct dir_context *ctx)
3808 {
3809 	struct inode *inode = file_inode(file);
3810 	struct task_struct *task;
3811 	struct pid_namespace *ns;
3812 	int tid;
3813 
3814 	if (proc_inode_is_dead(inode))
3815 		return -ENOENT;
3816 
3817 	if (!dir_emit_dots(file, ctx))
3818 		return 0;
3819 
3820 	/* f_version caches the tgid value that the last readdir call couldn't
3821 	 * return. lseek aka telldir automagically resets f_version to 0.
3822 	 */
3823 	ns = proc_pid_ns(inode->i_sb);
3824 	tid = (int)file->f_version;
3825 	file->f_version = 0;
3826 	for (task = first_tid(proc_pid(inode), tid, ctx->pos - 2, ns);
3827 	     task;
3828 	     task = next_tid(task), ctx->pos++) {
3829 		char name[10 + 1];
3830 		unsigned int len;
3831 		tid = task_pid_nr_ns(task, ns);
3832 		len = snprintf(name, sizeof(name), "%u", tid);
3833 		if (!proc_fill_cache(file, ctx, name, len,
3834 				proc_task_instantiate, task, NULL)) {
3835 			/* returning this tgid failed, save it as the first
3836 			 * pid for the next readir call */
3837 			file->f_version = (u64)tid;
3838 			put_task_struct(task);
3839 			break;
3840 		}
3841 	}
3842 
3843 	return 0;
3844 }
3845 
proc_task_getattr(const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)3846 static int proc_task_getattr(const struct path *path, struct kstat *stat,
3847 			     u32 request_mask, unsigned int query_flags)
3848 {
3849 	struct inode *inode = d_inode(path->dentry);
3850 	struct task_struct *p = get_proc_task(inode);
3851 	generic_fillattr(inode, stat);
3852 
3853 	if (p) {
3854 		stat->nlink += get_nr_threads(p);
3855 		put_task_struct(p);
3856 	}
3857 
3858 	return 0;
3859 }
3860 
3861 static const struct inode_operations proc_task_inode_operations = {
3862 	.lookup		= proc_task_lookup,
3863 	.getattr	= proc_task_getattr,
3864 	.setattr	= proc_setattr,
3865 	.permission	= proc_pid_permission,
3866 };
3867 
3868 static const struct file_operations proc_task_operations = {
3869 	.read		= generic_read_dir,
3870 	.iterate_shared	= proc_task_readdir,
3871 	.llseek		= generic_file_llseek,
3872 };
3873 
set_proc_pid_nlink(void)3874 void __init set_proc_pid_nlink(void)
3875 {
3876 	nlink_tid = pid_entry_nlink(tid_base_stuff, ARRAY_SIZE(tid_base_stuff));
3877 	nlink_tgid = pid_entry_nlink(tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff));
3878 }
3879