xref: /OK3568_Linux_fs/kernel/fs/proc/base.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
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 	if (S_ISDIR(mode)) {
1915 		spin_lock(&pid->lock);
1916 		hlist_add_head_rcu(&ei->sibling_inodes, &pid->inodes);
1917 		spin_unlock(&pid->lock);
1918 	}
1919 
1920 	task_dump_owner(task, 0, &inode->i_uid, &inode->i_gid);
1921 	security_task_to_inode(task, inode);
1922 
1923 out:
1924 	return inode;
1925 
1926 out_unlock:
1927 	iput(inode);
1928 	return NULL;
1929 }
1930 
pid_getattr(const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)1931 int pid_getattr(const struct path *path, struct kstat *stat,
1932 		u32 request_mask, unsigned int query_flags)
1933 {
1934 	struct inode *inode = d_inode(path->dentry);
1935 	struct proc_fs_info *fs_info = proc_sb_info(inode->i_sb);
1936 	struct task_struct *task;
1937 
1938 	generic_fillattr(inode, stat);
1939 
1940 	stat->uid = GLOBAL_ROOT_UID;
1941 	stat->gid = GLOBAL_ROOT_GID;
1942 	rcu_read_lock();
1943 	task = pid_task(proc_pid(inode), PIDTYPE_PID);
1944 	if (task) {
1945 		if (!has_pid_permissions(fs_info, task, HIDEPID_INVISIBLE)) {
1946 			rcu_read_unlock();
1947 			/*
1948 			 * This doesn't prevent learning whether PID exists,
1949 			 * it only makes getattr() consistent with readdir().
1950 			 */
1951 			return -ENOENT;
1952 		}
1953 		task_dump_owner(task, inode->i_mode, &stat->uid, &stat->gid);
1954 	}
1955 	rcu_read_unlock();
1956 	return 0;
1957 }
1958 
1959 /* dentry stuff */
1960 
1961 /*
1962  * Set <pid>/... inode ownership (can change due to setuid(), etc.)
1963  */
pid_update_inode(struct task_struct * task,struct inode * inode)1964 void pid_update_inode(struct task_struct *task, struct inode *inode)
1965 {
1966 	task_dump_owner(task, inode->i_mode, &inode->i_uid, &inode->i_gid);
1967 
1968 	inode->i_mode &= ~(S_ISUID | S_ISGID);
1969 	security_task_to_inode(task, inode);
1970 }
1971 
1972 /*
1973  * Rewrite the inode's ownerships here because the owning task may have
1974  * performed a setuid(), etc.
1975  *
1976  */
pid_revalidate(struct dentry * dentry,unsigned int flags)1977 static int pid_revalidate(struct dentry *dentry, unsigned int flags)
1978 {
1979 	struct inode *inode;
1980 	struct task_struct *task;
1981 
1982 	if (flags & LOOKUP_RCU)
1983 		return -ECHILD;
1984 
1985 	inode = d_inode(dentry);
1986 	task = get_proc_task(inode);
1987 
1988 	if (task) {
1989 		pid_update_inode(task, inode);
1990 		put_task_struct(task);
1991 		return 1;
1992 	}
1993 	return 0;
1994 }
1995 
proc_inode_is_dead(struct inode * inode)1996 static inline bool proc_inode_is_dead(struct inode *inode)
1997 {
1998 	return !proc_pid(inode)->tasks[PIDTYPE_PID].first;
1999 }
2000 
pid_delete_dentry(const struct dentry * dentry)2001 int pid_delete_dentry(const struct dentry *dentry)
2002 {
2003 	/* Is the task we represent dead?
2004 	 * If so, then don't put the dentry on the lru list,
2005 	 * kill it immediately.
2006 	 */
2007 	return proc_inode_is_dead(d_inode(dentry));
2008 }
2009 
2010 const struct dentry_operations pid_dentry_operations =
2011 {
2012 	.d_revalidate	= pid_revalidate,
2013 	.d_delete	= pid_delete_dentry,
2014 };
2015 
2016 /* Lookups */
2017 
2018 /*
2019  * Fill a directory entry.
2020  *
2021  * If possible create the dcache entry and derive our inode number and
2022  * file type from dcache entry.
2023  *
2024  * Since all of the proc inode numbers are dynamically generated, the inode
2025  * numbers do not exist until the inode is cache.  This means creating the
2026  * the dcache entry in readdir is necessary to keep the inode numbers
2027  * reported by readdir in sync with the inode numbers reported
2028  * by stat.
2029  */
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)2030 bool proc_fill_cache(struct file *file, struct dir_context *ctx,
2031 	const char *name, unsigned int len,
2032 	instantiate_t instantiate, struct task_struct *task, const void *ptr)
2033 {
2034 	struct dentry *child, *dir = file->f_path.dentry;
2035 	struct qstr qname = QSTR_INIT(name, len);
2036 	struct inode *inode;
2037 	unsigned type = DT_UNKNOWN;
2038 	ino_t ino = 1;
2039 
2040 	child = d_hash_and_lookup(dir, &qname);
2041 	if (!child) {
2042 		DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
2043 		child = d_alloc_parallel(dir, &qname, &wq);
2044 		if (IS_ERR(child))
2045 			goto end_instantiate;
2046 		if (d_in_lookup(child)) {
2047 			struct dentry *res;
2048 			res = instantiate(child, task, ptr);
2049 			d_lookup_done(child);
2050 			if (unlikely(res)) {
2051 				dput(child);
2052 				child = res;
2053 				if (IS_ERR(child))
2054 					goto end_instantiate;
2055 			}
2056 		}
2057 	}
2058 	inode = d_inode(child);
2059 	ino = inode->i_ino;
2060 	type = inode->i_mode >> 12;
2061 	dput(child);
2062 end_instantiate:
2063 	return dir_emit(ctx, name, len, ino, type);
2064 }
2065 
2066 /*
2067  * dname_to_vma_addr - maps a dentry name into two unsigned longs
2068  * which represent vma start and end addresses.
2069  */
dname_to_vma_addr(struct dentry * dentry,unsigned long * start,unsigned long * end)2070 static int dname_to_vma_addr(struct dentry *dentry,
2071 			     unsigned long *start, unsigned long *end)
2072 {
2073 	const char *str = dentry->d_name.name;
2074 	unsigned long long sval, eval;
2075 	unsigned int len;
2076 
2077 	if (str[0] == '0' && str[1] != '-')
2078 		return -EINVAL;
2079 	len = _parse_integer(str, 16, &sval);
2080 	if (len & KSTRTOX_OVERFLOW)
2081 		return -EINVAL;
2082 	if (sval != (unsigned long)sval)
2083 		return -EINVAL;
2084 	str += len;
2085 
2086 	if (*str != '-')
2087 		return -EINVAL;
2088 	str++;
2089 
2090 	if (str[0] == '0' && str[1])
2091 		return -EINVAL;
2092 	len = _parse_integer(str, 16, &eval);
2093 	if (len & KSTRTOX_OVERFLOW)
2094 		return -EINVAL;
2095 	if (eval != (unsigned long)eval)
2096 		return -EINVAL;
2097 	str += len;
2098 
2099 	if (*str != '\0')
2100 		return -EINVAL;
2101 
2102 	*start = sval;
2103 	*end = eval;
2104 
2105 	return 0;
2106 }
2107 
map_files_d_revalidate(struct dentry * dentry,unsigned int flags)2108 static int map_files_d_revalidate(struct dentry *dentry, unsigned int flags)
2109 {
2110 	unsigned long vm_start, vm_end;
2111 	bool exact_vma_exists = false;
2112 	struct mm_struct *mm = NULL;
2113 	struct task_struct *task;
2114 	struct inode *inode;
2115 	int status = 0;
2116 
2117 	if (flags & LOOKUP_RCU)
2118 		return -ECHILD;
2119 
2120 	inode = d_inode(dentry);
2121 	task = get_proc_task(inode);
2122 	if (!task)
2123 		goto out_notask;
2124 
2125 	mm = mm_access(task, PTRACE_MODE_READ_FSCREDS);
2126 	if (IS_ERR_OR_NULL(mm))
2127 		goto out;
2128 
2129 	if (!dname_to_vma_addr(dentry, &vm_start, &vm_end)) {
2130 		status = mmap_read_lock_killable(mm);
2131 		if (!status) {
2132 			exact_vma_exists = !!find_exact_vma(mm, vm_start,
2133 							    vm_end);
2134 			mmap_read_unlock(mm);
2135 		}
2136 	}
2137 
2138 	mmput(mm);
2139 
2140 	if (exact_vma_exists) {
2141 		task_dump_owner(task, 0, &inode->i_uid, &inode->i_gid);
2142 
2143 		security_task_to_inode(task, inode);
2144 		status = 1;
2145 	}
2146 
2147 out:
2148 	put_task_struct(task);
2149 
2150 out_notask:
2151 	return status;
2152 }
2153 
2154 static const struct dentry_operations tid_map_files_dentry_operations = {
2155 	.d_revalidate	= map_files_d_revalidate,
2156 	.d_delete	= pid_delete_dentry,
2157 };
2158 
map_files_get_link(struct dentry * dentry,struct path * path)2159 static int map_files_get_link(struct dentry *dentry, struct path *path)
2160 {
2161 	unsigned long vm_start, vm_end;
2162 	struct vm_area_struct *vma;
2163 	struct task_struct *task;
2164 	struct mm_struct *mm;
2165 	int rc;
2166 
2167 	rc = -ENOENT;
2168 	task = get_proc_task(d_inode(dentry));
2169 	if (!task)
2170 		goto out;
2171 
2172 	mm = get_task_mm(task);
2173 	put_task_struct(task);
2174 	if (!mm)
2175 		goto out;
2176 
2177 	rc = dname_to_vma_addr(dentry, &vm_start, &vm_end);
2178 	if (rc)
2179 		goto out_mmput;
2180 
2181 	rc = mmap_read_lock_killable(mm);
2182 	if (rc)
2183 		goto out_mmput;
2184 
2185 	rc = -ENOENT;
2186 	vma = find_exact_vma(mm, vm_start, vm_end);
2187 	if (vma && vma->vm_file) {
2188 		*path = vma->vm_file->f_path;
2189 		path_get(path);
2190 		rc = 0;
2191 	}
2192 	mmap_read_unlock(mm);
2193 
2194 out_mmput:
2195 	mmput(mm);
2196 out:
2197 	return rc;
2198 }
2199 
2200 struct map_files_info {
2201 	unsigned long	start;
2202 	unsigned long	end;
2203 	fmode_t		mode;
2204 };
2205 
2206 /*
2207  * Only allow CAP_SYS_ADMIN and CAP_CHECKPOINT_RESTORE to follow the links, due
2208  * to concerns about how the symlinks may be used to bypass permissions on
2209  * ancestor directories in the path to the file in question.
2210  */
2211 static const char *
proc_map_files_get_link(struct dentry * dentry,struct inode * inode,struct delayed_call * done)2212 proc_map_files_get_link(struct dentry *dentry,
2213 			struct inode *inode,
2214 		        struct delayed_call *done)
2215 {
2216 	if (!checkpoint_restore_ns_capable(&init_user_ns))
2217 		return ERR_PTR(-EPERM);
2218 
2219 	return proc_pid_get_link(dentry, inode, done);
2220 }
2221 
2222 /*
2223  * Identical to proc_pid_link_inode_operations except for get_link()
2224  */
2225 static const struct inode_operations proc_map_files_link_inode_operations = {
2226 	.readlink	= proc_pid_readlink,
2227 	.get_link	= proc_map_files_get_link,
2228 	.setattr	= proc_setattr,
2229 };
2230 
2231 static struct dentry *
proc_map_files_instantiate(struct dentry * dentry,struct task_struct * task,const void * ptr)2232 proc_map_files_instantiate(struct dentry *dentry,
2233 			   struct task_struct *task, const void *ptr)
2234 {
2235 	fmode_t mode = (fmode_t)(unsigned long)ptr;
2236 	struct proc_inode *ei;
2237 	struct inode *inode;
2238 
2239 	inode = proc_pid_make_inode(dentry->d_sb, task, S_IFLNK |
2240 				    ((mode & FMODE_READ ) ? S_IRUSR : 0) |
2241 				    ((mode & FMODE_WRITE) ? S_IWUSR : 0));
2242 	if (!inode)
2243 		return ERR_PTR(-ENOENT);
2244 
2245 	ei = PROC_I(inode);
2246 	ei->op.proc_get_link = map_files_get_link;
2247 
2248 	inode->i_op = &proc_map_files_link_inode_operations;
2249 	inode->i_size = 64;
2250 
2251 	d_set_d_op(dentry, &tid_map_files_dentry_operations);
2252 	return d_splice_alias(inode, dentry);
2253 }
2254 
proc_map_files_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)2255 static struct dentry *proc_map_files_lookup(struct inode *dir,
2256 		struct dentry *dentry, unsigned int flags)
2257 {
2258 	unsigned long vm_start, vm_end;
2259 	struct vm_area_struct *vma;
2260 	struct task_struct *task;
2261 	struct dentry *result;
2262 	struct mm_struct *mm;
2263 
2264 	result = ERR_PTR(-ENOENT);
2265 	task = get_proc_task(dir);
2266 	if (!task)
2267 		goto out;
2268 
2269 	result = ERR_PTR(-EACCES);
2270 	if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
2271 		goto out_put_task;
2272 
2273 	result = ERR_PTR(-ENOENT);
2274 	if (dname_to_vma_addr(dentry, &vm_start, &vm_end))
2275 		goto out_put_task;
2276 
2277 	mm = get_task_mm(task);
2278 	if (!mm)
2279 		goto out_put_task;
2280 
2281 	result = ERR_PTR(-EINTR);
2282 	if (mmap_read_lock_killable(mm))
2283 		goto out_put_mm;
2284 
2285 	result = ERR_PTR(-ENOENT);
2286 	vma = find_exact_vma(mm, vm_start, vm_end);
2287 	if (!vma)
2288 		goto out_no_vma;
2289 
2290 	if (vma->vm_file)
2291 		result = proc_map_files_instantiate(dentry, task,
2292 				(void *)(unsigned long)vma->vm_file->f_mode);
2293 
2294 out_no_vma:
2295 	mmap_read_unlock(mm);
2296 out_put_mm:
2297 	mmput(mm);
2298 out_put_task:
2299 	put_task_struct(task);
2300 out:
2301 	return result;
2302 }
2303 
2304 static const struct inode_operations proc_map_files_inode_operations = {
2305 	.lookup		= proc_map_files_lookup,
2306 	.permission	= proc_fd_permission,
2307 	.setattr	= proc_setattr,
2308 };
2309 
2310 static int
proc_map_files_readdir(struct file * file,struct dir_context * ctx)2311 proc_map_files_readdir(struct file *file, struct dir_context *ctx)
2312 {
2313 	struct vm_area_struct *vma;
2314 	struct task_struct *task;
2315 	struct mm_struct *mm;
2316 	unsigned long nr_files, pos, i;
2317 	GENRADIX(struct map_files_info) fa;
2318 	struct map_files_info *p;
2319 	int ret;
2320 
2321 	genradix_init(&fa);
2322 
2323 	ret = -ENOENT;
2324 	task = get_proc_task(file_inode(file));
2325 	if (!task)
2326 		goto out;
2327 
2328 	ret = -EACCES;
2329 	if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
2330 		goto out_put_task;
2331 
2332 	ret = 0;
2333 	if (!dir_emit_dots(file, ctx))
2334 		goto out_put_task;
2335 
2336 	mm = get_task_mm(task);
2337 	if (!mm)
2338 		goto out_put_task;
2339 
2340 	ret = mmap_read_lock_killable(mm);
2341 	if (ret) {
2342 		mmput(mm);
2343 		goto out_put_task;
2344 	}
2345 
2346 	nr_files = 0;
2347 
2348 	/*
2349 	 * We need two passes here:
2350 	 *
2351 	 *  1) Collect vmas of mapped files with mmap_lock taken
2352 	 *  2) Release mmap_lock and instantiate entries
2353 	 *
2354 	 * otherwise we get lockdep complained, since filldir()
2355 	 * routine might require mmap_lock taken in might_fault().
2356 	 */
2357 
2358 	for (vma = mm->mmap, pos = 2; vma; vma = vma->vm_next) {
2359 		if (!vma->vm_file)
2360 			continue;
2361 		if (++pos <= ctx->pos)
2362 			continue;
2363 
2364 		p = genradix_ptr_alloc(&fa, nr_files++, GFP_KERNEL);
2365 		if (!p) {
2366 			ret = -ENOMEM;
2367 			mmap_read_unlock(mm);
2368 			mmput(mm);
2369 			goto out_put_task;
2370 		}
2371 
2372 		p->start = vma->vm_start;
2373 		p->end = vma->vm_end;
2374 		p->mode = vma->vm_file->f_mode;
2375 	}
2376 	mmap_read_unlock(mm);
2377 	mmput(mm);
2378 
2379 	for (i = 0; i < nr_files; i++) {
2380 		char buf[4 * sizeof(long) + 2];	/* max: %lx-%lx\0 */
2381 		unsigned int len;
2382 
2383 		p = genradix_ptr(&fa, i);
2384 		len = snprintf(buf, sizeof(buf), "%lx-%lx", p->start, p->end);
2385 		if (!proc_fill_cache(file, ctx,
2386 				      buf, len,
2387 				      proc_map_files_instantiate,
2388 				      task,
2389 				      (void *)(unsigned long)p->mode))
2390 			break;
2391 		ctx->pos++;
2392 	}
2393 
2394 out_put_task:
2395 	put_task_struct(task);
2396 out:
2397 	genradix_free(&fa);
2398 	return ret;
2399 }
2400 
2401 static const struct file_operations proc_map_files_operations = {
2402 	.read		= generic_read_dir,
2403 	.iterate_shared	= proc_map_files_readdir,
2404 	.llseek		= generic_file_llseek,
2405 };
2406 
2407 #if defined(CONFIG_CHECKPOINT_RESTORE) && defined(CONFIG_POSIX_TIMERS)
2408 struct timers_private {
2409 	struct pid *pid;
2410 	struct task_struct *task;
2411 	struct sighand_struct *sighand;
2412 	struct pid_namespace *ns;
2413 	unsigned long flags;
2414 };
2415 
timers_start(struct seq_file * m,loff_t * pos)2416 static void *timers_start(struct seq_file *m, loff_t *pos)
2417 {
2418 	struct timers_private *tp = m->private;
2419 
2420 	tp->task = get_pid_task(tp->pid, PIDTYPE_PID);
2421 	if (!tp->task)
2422 		return ERR_PTR(-ESRCH);
2423 
2424 	tp->sighand = lock_task_sighand(tp->task, &tp->flags);
2425 	if (!tp->sighand)
2426 		return ERR_PTR(-ESRCH);
2427 
2428 	return seq_list_start(&tp->task->signal->posix_timers, *pos);
2429 }
2430 
timers_next(struct seq_file * m,void * v,loff_t * pos)2431 static void *timers_next(struct seq_file *m, void *v, loff_t *pos)
2432 {
2433 	struct timers_private *tp = m->private;
2434 	return seq_list_next(v, &tp->task->signal->posix_timers, pos);
2435 }
2436 
timers_stop(struct seq_file * m,void * v)2437 static void timers_stop(struct seq_file *m, void *v)
2438 {
2439 	struct timers_private *tp = m->private;
2440 
2441 	if (tp->sighand) {
2442 		unlock_task_sighand(tp->task, &tp->flags);
2443 		tp->sighand = NULL;
2444 	}
2445 
2446 	if (tp->task) {
2447 		put_task_struct(tp->task);
2448 		tp->task = NULL;
2449 	}
2450 }
2451 
show_timer(struct seq_file * m,void * v)2452 static int show_timer(struct seq_file *m, void *v)
2453 {
2454 	struct k_itimer *timer;
2455 	struct timers_private *tp = m->private;
2456 	int notify;
2457 	static const char * const nstr[] = {
2458 		[SIGEV_SIGNAL] = "signal",
2459 		[SIGEV_NONE] = "none",
2460 		[SIGEV_THREAD] = "thread",
2461 	};
2462 
2463 	timer = list_entry((struct list_head *)v, struct k_itimer, list);
2464 	notify = timer->it_sigev_notify;
2465 
2466 	seq_printf(m, "ID: %d\n", timer->it_id);
2467 	seq_printf(m, "signal: %d/%px\n",
2468 		   timer->sigq->info.si_signo,
2469 		   timer->sigq->info.si_value.sival_ptr);
2470 	seq_printf(m, "notify: %s/%s.%d\n",
2471 		   nstr[notify & ~SIGEV_THREAD_ID],
2472 		   (notify & SIGEV_THREAD_ID) ? "tid" : "pid",
2473 		   pid_nr_ns(timer->it_pid, tp->ns));
2474 	seq_printf(m, "ClockID: %d\n", timer->it_clock);
2475 
2476 	return 0;
2477 }
2478 
2479 static const struct seq_operations proc_timers_seq_ops = {
2480 	.start	= timers_start,
2481 	.next	= timers_next,
2482 	.stop	= timers_stop,
2483 	.show	= show_timer,
2484 };
2485 
proc_timers_open(struct inode * inode,struct file * file)2486 static int proc_timers_open(struct inode *inode, struct file *file)
2487 {
2488 	struct timers_private *tp;
2489 
2490 	tp = __seq_open_private(file, &proc_timers_seq_ops,
2491 			sizeof(struct timers_private));
2492 	if (!tp)
2493 		return -ENOMEM;
2494 
2495 	tp->pid = proc_pid(inode);
2496 	tp->ns = proc_pid_ns(inode->i_sb);
2497 	return 0;
2498 }
2499 
2500 static const struct file_operations proc_timers_operations = {
2501 	.open		= proc_timers_open,
2502 	.read		= seq_read,
2503 	.llseek		= seq_lseek,
2504 	.release	= seq_release_private,
2505 };
2506 #endif
2507 
timerslack_ns_write(struct file * file,const char __user * buf,size_t count,loff_t * offset)2508 static ssize_t timerslack_ns_write(struct file *file, const char __user *buf,
2509 					size_t count, loff_t *offset)
2510 {
2511 	struct inode *inode = file_inode(file);
2512 	struct task_struct *p;
2513 	u64 slack_ns;
2514 	int err;
2515 
2516 	err = kstrtoull_from_user(buf, count, 10, &slack_ns);
2517 	if (err < 0)
2518 		return err;
2519 
2520 	p = get_proc_task(inode);
2521 	if (!p)
2522 		return -ESRCH;
2523 
2524 	if (p != current) {
2525 		rcu_read_lock();
2526 		if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
2527 			rcu_read_unlock();
2528 			count = -EPERM;
2529 			goto out;
2530 		}
2531 		rcu_read_unlock();
2532 
2533 		err = security_task_setscheduler(p);
2534 		if (err) {
2535 			count = err;
2536 			goto out;
2537 		}
2538 	}
2539 
2540 	task_lock(p);
2541 	if (slack_ns == 0)
2542 		p->timer_slack_ns = p->default_timer_slack_ns;
2543 	else
2544 		p->timer_slack_ns = slack_ns;
2545 	task_unlock(p);
2546 
2547 out:
2548 	put_task_struct(p);
2549 
2550 	return count;
2551 }
2552 
timerslack_ns_show(struct seq_file * m,void * v)2553 static int timerslack_ns_show(struct seq_file *m, void *v)
2554 {
2555 	struct inode *inode = m->private;
2556 	struct task_struct *p;
2557 	int err = 0;
2558 
2559 	p = get_proc_task(inode);
2560 	if (!p)
2561 		return -ESRCH;
2562 
2563 	if (p != current) {
2564 		rcu_read_lock();
2565 		if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
2566 			rcu_read_unlock();
2567 			err = -EPERM;
2568 			goto out;
2569 		}
2570 		rcu_read_unlock();
2571 
2572 		err = security_task_getscheduler(p);
2573 		if (err)
2574 			goto out;
2575 	}
2576 
2577 	task_lock(p);
2578 	seq_printf(m, "%llu\n", p->timer_slack_ns);
2579 	task_unlock(p);
2580 
2581 out:
2582 	put_task_struct(p);
2583 
2584 	return err;
2585 }
2586 
timerslack_ns_open(struct inode * inode,struct file * filp)2587 static int timerslack_ns_open(struct inode *inode, struct file *filp)
2588 {
2589 	return single_open(filp, timerslack_ns_show, inode);
2590 }
2591 
2592 static const struct file_operations proc_pid_set_timerslack_ns_operations = {
2593 	.open		= timerslack_ns_open,
2594 	.read		= seq_read,
2595 	.write		= timerslack_ns_write,
2596 	.llseek		= seq_lseek,
2597 	.release	= single_release,
2598 };
2599 
proc_pident_instantiate(struct dentry * dentry,struct task_struct * task,const void * ptr)2600 static struct dentry *proc_pident_instantiate(struct dentry *dentry,
2601 	struct task_struct *task, const void *ptr)
2602 {
2603 	const struct pid_entry *p = ptr;
2604 	struct inode *inode;
2605 	struct proc_inode *ei;
2606 
2607 	inode = proc_pid_make_inode(dentry->d_sb, task, p->mode);
2608 	if (!inode)
2609 		return ERR_PTR(-ENOENT);
2610 
2611 	ei = PROC_I(inode);
2612 	if (S_ISDIR(inode->i_mode))
2613 		set_nlink(inode, 2);	/* Use getattr to fix if necessary */
2614 	if (p->iop)
2615 		inode->i_op = p->iop;
2616 	if (p->fop)
2617 		inode->i_fop = p->fop;
2618 	ei->op = p->op;
2619 	pid_update_inode(task, inode);
2620 	d_set_d_op(dentry, &pid_dentry_operations);
2621 	return d_splice_alias(inode, dentry);
2622 }
2623 
proc_pident_lookup(struct inode * dir,struct dentry * dentry,const struct pid_entry * p,const struct pid_entry * end)2624 static struct dentry *proc_pident_lookup(struct inode *dir,
2625 					 struct dentry *dentry,
2626 					 const struct pid_entry *p,
2627 					 const struct pid_entry *end)
2628 {
2629 	struct task_struct *task = get_proc_task(dir);
2630 	struct dentry *res = ERR_PTR(-ENOENT);
2631 
2632 	if (!task)
2633 		goto out_no_task;
2634 
2635 	/*
2636 	 * Yes, it does not scale. And it should not. Don't add
2637 	 * new entries into /proc/<tgid>/ without very good reasons.
2638 	 */
2639 	for (; p < end; p++) {
2640 		if (p->len != dentry->d_name.len)
2641 			continue;
2642 		if (!memcmp(dentry->d_name.name, p->name, p->len)) {
2643 			res = proc_pident_instantiate(dentry, task, p);
2644 			break;
2645 		}
2646 	}
2647 	put_task_struct(task);
2648 out_no_task:
2649 	return res;
2650 }
2651 
proc_pident_readdir(struct file * file,struct dir_context * ctx,const struct pid_entry * ents,unsigned int nents)2652 static int proc_pident_readdir(struct file *file, struct dir_context *ctx,
2653 		const struct pid_entry *ents, unsigned int nents)
2654 {
2655 	struct task_struct *task = get_proc_task(file_inode(file));
2656 	const struct pid_entry *p;
2657 
2658 	if (!task)
2659 		return -ENOENT;
2660 
2661 	if (!dir_emit_dots(file, ctx))
2662 		goto out;
2663 
2664 	if (ctx->pos >= nents + 2)
2665 		goto out;
2666 
2667 	for (p = ents + (ctx->pos - 2); p < ents + nents; p++) {
2668 		if (!proc_fill_cache(file, ctx, p->name, p->len,
2669 				proc_pident_instantiate, task, p))
2670 			break;
2671 		ctx->pos++;
2672 	}
2673 out:
2674 	put_task_struct(task);
2675 	return 0;
2676 }
2677 
2678 #ifdef CONFIG_SECURITY
proc_pid_attr_open(struct inode * inode,struct file * file)2679 static int proc_pid_attr_open(struct inode *inode, struct file *file)
2680 {
2681 	file->private_data = NULL;
2682 	__mem_open(inode, file, PTRACE_MODE_READ_FSCREDS);
2683 	return 0;
2684 }
2685 
proc_pid_attr_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)2686 static ssize_t proc_pid_attr_read(struct file * file, char __user * buf,
2687 				  size_t count, loff_t *ppos)
2688 {
2689 	struct inode * inode = file_inode(file);
2690 	char *p = NULL;
2691 	ssize_t length;
2692 	struct task_struct *task = get_proc_task(inode);
2693 
2694 	if (!task)
2695 		return -ESRCH;
2696 
2697 	length = security_getprocattr(task, PROC_I(inode)->op.lsm,
2698 				      (char*)file->f_path.dentry->d_name.name,
2699 				      &p);
2700 	put_task_struct(task);
2701 	if (length > 0)
2702 		length = simple_read_from_buffer(buf, count, ppos, p, length);
2703 	kfree(p);
2704 	return length;
2705 }
2706 
proc_pid_attr_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)2707 static ssize_t proc_pid_attr_write(struct file * file, const char __user * buf,
2708 				   size_t count, loff_t *ppos)
2709 {
2710 	struct inode * inode = file_inode(file);
2711 	struct task_struct *task;
2712 	void *page;
2713 	int rv;
2714 
2715 	/* A task may only write when it was the opener. */
2716 	if (file->private_data != current->mm)
2717 		return -EPERM;
2718 
2719 	rcu_read_lock();
2720 	task = pid_task(proc_pid(inode), PIDTYPE_PID);
2721 	if (!task) {
2722 		rcu_read_unlock();
2723 		return -ESRCH;
2724 	}
2725 	/* A task may only write its own attributes. */
2726 	if (current != task) {
2727 		rcu_read_unlock();
2728 		return -EACCES;
2729 	}
2730 	/* Prevent changes to overridden credentials. */
2731 	if (current_cred() != current_real_cred()) {
2732 		rcu_read_unlock();
2733 		return -EBUSY;
2734 	}
2735 	rcu_read_unlock();
2736 
2737 	if (count > PAGE_SIZE)
2738 		count = PAGE_SIZE;
2739 
2740 	/* No partial writes. */
2741 	if (*ppos != 0)
2742 		return -EINVAL;
2743 
2744 	page = memdup_user(buf, count);
2745 	if (IS_ERR(page)) {
2746 		rv = PTR_ERR(page);
2747 		goto out;
2748 	}
2749 
2750 	/* Guard against adverse ptrace interaction */
2751 	rv = mutex_lock_interruptible(&current->signal->cred_guard_mutex);
2752 	if (rv < 0)
2753 		goto out_free;
2754 
2755 	rv = security_setprocattr(PROC_I(inode)->op.lsm,
2756 				  file->f_path.dentry->d_name.name, page,
2757 				  count);
2758 	mutex_unlock(&current->signal->cred_guard_mutex);
2759 out_free:
2760 	kfree(page);
2761 out:
2762 	return rv;
2763 }
2764 
2765 static const struct file_operations proc_pid_attr_operations = {
2766 	.open		= proc_pid_attr_open,
2767 	.read		= proc_pid_attr_read,
2768 	.write		= proc_pid_attr_write,
2769 	.llseek		= generic_file_llseek,
2770 	.release	= mem_release,
2771 };
2772 
2773 #define LSM_DIR_OPS(LSM) \
2774 static int proc_##LSM##_attr_dir_iterate(struct file *filp, \
2775 			     struct dir_context *ctx) \
2776 { \
2777 	return proc_pident_readdir(filp, ctx, \
2778 				   LSM##_attr_dir_stuff, \
2779 				   ARRAY_SIZE(LSM##_attr_dir_stuff)); \
2780 } \
2781 \
2782 static const struct file_operations proc_##LSM##_attr_dir_ops = { \
2783 	.read		= generic_read_dir, \
2784 	.iterate	= proc_##LSM##_attr_dir_iterate, \
2785 	.llseek		= default_llseek, \
2786 }; \
2787 \
2788 static struct dentry *proc_##LSM##_attr_dir_lookup(struct inode *dir, \
2789 				struct dentry *dentry, unsigned int flags) \
2790 { \
2791 	return proc_pident_lookup(dir, dentry, \
2792 				  LSM##_attr_dir_stuff, \
2793 				  LSM##_attr_dir_stuff + ARRAY_SIZE(LSM##_attr_dir_stuff)); \
2794 } \
2795 \
2796 static const struct inode_operations proc_##LSM##_attr_dir_inode_ops = { \
2797 	.lookup		= proc_##LSM##_attr_dir_lookup, \
2798 	.getattr	= pid_getattr, \
2799 	.setattr	= proc_setattr, \
2800 }
2801 
2802 #ifdef CONFIG_SECURITY_SMACK
2803 static const struct pid_entry smack_attr_dir_stuff[] = {
2804 	ATTR("smack", "current",	0666),
2805 };
2806 LSM_DIR_OPS(smack);
2807 #endif
2808 
2809 #ifdef CONFIG_SECURITY_APPARMOR
2810 static const struct pid_entry apparmor_attr_dir_stuff[] = {
2811 	ATTR("apparmor", "current",	0666),
2812 	ATTR("apparmor", "prev",	0444),
2813 	ATTR("apparmor", "exec",	0666),
2814 };
2815 LSM_DIR_OPS(apparmor);
2816 #endif
2817 
2818 static const struct pid_entry attr_dir_stuff[] = {
2819 	ATTR(NULL, "current",		0666),
2820 	ATTR(NULL, "prev",		0444),
2821 	ATTR(NULL, "exec",		0666),
2822 	ATTR(NULL, "fscreate",		0666),
2823 	ATTR(NULL, "keycreate",		0666),
2824 	ATTR(NULL, "sockcreate",	0666),
2825 #ifdef CONFIG_SECURITY_SMACK
2826 	DIR("smack",			0555,
2827 	    proc_smack_attr_dir_inode_ops, proc_smack_attr_dir_ops),
2828 #endif
2829 #ifdef CONFIG_SECURITY_APPARMOR
2830 	DIR("apparmor",			0555,
2831 	    proc_apparmor_attr_dir_inode_ops, proc_apparmor_attr_dir_ops),
2832 #endif
2833 };
2834 
proc_attr_dir_readdir(struct file * file,struct dir_context * ctx)2835 static int proc_attr_dir_readdir(struct file *file, struct dir_context *ctx)
2836 {
2837 	return proc_pident_readdir(file, ctx,
2838 				   attr_dir_stuff, ARRAY_SIZE(attr_dir_stuff));
2839 }
2840 
2841 static const struct file_operations proc_attr_dir_operations = {
2842 	.read		= generic_read_dir,
2843 	.iterate_shared	= proc_attr_dir_readdir,
2844 	.llseek		= generic_file_llseek,
2845 };
2846 
proc_attr_dir_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)2847 static struct dentry *proc_attr_dir_lookup(struct inode *dir,
2848 				struct dentry *dentry, unsigned int flags)
2849 {
2850 	return proc_pident_lookup(dir, dentry,
2851 				  attr_dir_stuff,
2852 				  attr_dir_stuff + ARRAY_SIZE(attr_dir_stuff));
2853 }
2854 
2855 static const struct inode_operations proc_attr_dir_inode_operations = {
2856 	.lookup		= proc_attr_dir_lookup,
2857 	.getattr	= pid_getattr,
2858 	.setattr	= proc_setattr,
2859 };
2860 
2861 #endif
2862 
2863 #ifdef CONFIG_ELF_CORE
proc_coredump_filter_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)2864 static ssize_t proc_coredump_filter_read(struct file *file, char __user *buf,
2865 					 size_t count, loff_t *ppos)
2866 {
2867 	struct task_struct *task = get_proc_task(file_inode(file));
2868 	struct mm_struct *mm;
2869 	char buffer[PROC_NUMBUF];
2870 	size_t len;
2871 	int ret;
2872 
2873 	if (!task)
2874 		return -ESRCH;
2875 
2876 	ret = 0;
2877 	mm = get_task_mm(task);
2878 	if (mm) {
2879 		len = snprintf(buffer, sizeof(buffer), "%08lx\n",
2880 			       ((mm->flags & MMF_DUMP_FILTER_MASK) >>
2881 				MMF_DUMP_FILTER_SHIFT));
2882 		mmput(mm);
2883 		ret = simple_read_from_buffer(buf, count, ppos, buffer, len);
2884 	}
2885 
2886 	put_task_struct(task);
2887 
2888 	return ret;
2889 }
2890 
proc_coredump_filter_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)2891 static ssize_t proc_coredump_filter_write(struct file *file,
2892 					  const char __user *buf,
2893 					  size_t count,
2894 					  loff_t *ppos)
2895 {
2896 	struct task_struct *task;
2897 	struct mm_struct *mm;
2898 	unsigned int val;
2899 	int ret;
2900 	int i;
2901 	unsigned long mask;
2902 
2903 	ret = kstrtouint_from_user(buf, count, 0, &val);
2904 	if (ret < 0)
2905 		return ret;
2906 
2907 	ret = -ESRCH;
2908 	task = get_proc_task(file_inode(file));
2909 	if (!task)
2910 		goto out_no_task;
2911 
2912 	mm = get_task_mm(task);
2913 	if (!mm)
2914 		goto out_no_mm;
2915 	ret = 0;
2916 
2917 	for (i = 0, mask = 1; i < MMF_DUMP_FILTER_BITS; i++, mask <<= 1) {
2918 		if (val & mask)
2919 			set_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
2920 		else
2921 			clear_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
2922 	}
2923 
2924 	mmput(mm);
2925  out_no_mm:
2926 	put_task_struct(task);
2927  out_no_task:
2928 	if (ret < 0)
2929 		return ret;
2930 	return count;
2931 }
2932 
2933 static const struct file_operations proc_coredump_filter_operations = {
2934 	.read		= proc_coredump_filter_read,
2935 	.write		= proc_coredump_filter_write,
2936 	.llseek		= generic_file_llseek,
2937 };
2938 #endif
2939 
2940 #ifdef CONFIG_TASK_IO_ACCOUNTING
do_io_accounting(struct task_struct * task,struct seq_file * m,int whole)2941 static int do_io_accounting(struct task_struct *task, struct seq_file *m, int whole)
2942 {
2943 	struct task_io_accounting acct = task->ioac;
2944 	unsigned long flags;
2945 	int result;
2946 
2947 	result = down_read_killable(&task->signal->exec_update_lock);
2948 	if (result)
2949 		return result;
2950 
2951 	if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS)) {
2952 		result = -EACCES;
2953 		goto out_unlock;
2954 	}
2955 
2956 	if (whole && lock_task_sighand(task, &flags)) {
2957 		struct task_struct *t = task;
2958 
2959 		task_io_accounting_add(&acct, &task->signal->ioac);
2960 		while_each_thread(task, t)
2961 			task_io_accounting_add(&acct, &t->ioac);
2962 
2963 		unlock_task_sighand(task, &flags);
2964 	}
2965 	seq_printf(m,
2966 		   "rchar: %llu\n"
2967 		   "wchar: %llu\n"
2968 		   "syscr: %llu\n"
2969 		   "syscw: %llu\n"
2970 		   "read_bytes: %llu\n"
2971 		   "write_bytes: %llu\n"
2972 		   "cancelled_write_bytes: %llu\n",
2973 		   (unsigned long long)acct.rchar,
2974 		   (unsigned long long)acct.wchar,
2975 		   (unsigned long long)acct.syscr,
2976 		   (unsigned long long)acct.syscw,
2977 		   (unsigned long long)acct.read_bytes,
2978 		   (unsigned long long)acct.write_bytes,
2979 		   (unsigned long long)acct.cancelled_write_bytes);
2980 	result = 0;
2981 
2982 out_unlock:
2983 	up_read(&task->signal->exec_update_lock);
2984 	return result;
2985 }
2986 
proc_tid_io_accounting(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)2987 static int proc_tid_io_accounting(struct seq_file *m, struct pid_namespace *ns,
2988 				  struct pid *pid, struct task_struct *task)
2989 {
2990 	return do_io_accounting(task, m, 0);
2991 }
2992 
proc_tgid_io_accounting(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)2993 static int proc_tgid_io_accounting(struct seq_file *m, struct pid_namespace *ns,
2994 				   struct pid *pid, struct task_struct *task)
2995 {
2996 	return do_io_accounting(task, m, 1);
2997 }
2998 #endif /* CONFIG_TASK_IO_ACCOUNTING */
2999 
3000 #ifdef CONFIG_USER_NS
proc_id_map_open(struct inode * inode,struct file * file,const struct seq_operations * seq_ops)3001 static int proc_id_map_open(struct inode *inode, struct file *file,
3002 	const struct seq_operations *seq_ops)
3003 {
3004 	struct user_namespace *ns = NULL;
3005 	struct task_struct *task;
3006 	struct seq_file *seq;
3007 	int ret = -EINVAL;
3008 
3009 	task = get_proc_task(inode);
3010 	if (task) {
3011 		rcu_read_lock();
3012 		ns = get_user_ns(task_cred_xxx(task, user_ns));
3013 		rcu_read_unlock();
3014 		put_task_struct(task);
3015 	}
3016 	if (!ns)
3017 		goto err;
3018 
3019 	ret = seq_open(file, seq_ops);
3020 	if (ret)
3021 		goto err_put_ns;
3022 
3023 	seq = file->private_data;
3024 	seq->private = ns;
3025 
3026 	return 0;
3027 err_put_ns:
3028 	put_user_ns(ns);
3029 err:
3030 	return ret;
3031 }
3032 
proc_id_map_release(struct inode * inode,struct file * file)3033 static int proc_id_map_release(struct inode *inode, struct file *file)
3034 {
3035 	struct seq_file *seq = file->private_data;
3036 	struct user_namespace *ns = seq->private;
3037 	put_user_ns(ns);
3038 	return seq_release(inode, file);
3039 }
3040 
proc_uid_map_open(struct inode * inode,struct file * file)3041 static int proc_uid_map_open(struct inode *inode, struct file *file)
3042 {
3043 	return proc_id_map_open(inode, file, &proc_uid_seq_operations);
3044 }
3045 
proc_gid_map_open(struct inode * inode,struct file * file)3046 static int proc_gid_map_open(struct inode *inode, struct file *file)
3047 {
3048 	return proc_id_map_open(inode, file, &proc_gid_seq_operations);
3049 }
3050 
proc_projid_map_open(struct inode * inode,struct file * file)3051 static int proc_projid_map_open(struct inode *inode, struct file *file)
3052 {
3053 	return proc_id_map_open(inode, file, &proc_projid_seq_operations);
3054 }
3055 
3056 static const struct file_operations proc_uid_map_operations = {
3057 	.open		= proc_uid_map_open,
3058 	.write		= proc_uid_map_write,
3059 	.read		= seq_read,
3060 	.llseek		= seq_lseek,
3061 	.release	= proc_id_map_release,
3062 };
3063 
3064 static const struct file_operations proc_gid_map_operations = {
3065 	.open		= proc_gid_map_open,
3066 	.write		= proc_gid_map_write,
3067 	.read		= seq_read,
3068 	.llseek		= seq_lseek,
3069 	.release	= proc_id_map_release,
3070 };
3071 
3072 static const struct file_operations proc_projid_map_operations = {
3073 	.open		= proc_projid_map_open,
3074 	.write		= proc_projid_map_write,
3075 	.read		= seq_read,
3076 	.llseek		= seq_lseek,
3077 	.release	= proc_id_map_release,
3078 };
3079 
proc_setgroups_open(struct inode * inode,struct file * file)3080 static int proc_setgroups_open(struct inode *inode, struct file *file)
3081 {
3082 	struct user_namespace *ns = NULL;
3083 	struct task_struct *task;
3084 	int ret;
3085 
3086 	ret = -ESRCH;
3087 	task = get_proc_task(inode);
3088 	if (task) {
3089 		rcu_read_lock();
3090 		ns = get_user_ns(task_cred_xxx(task, user_ns));
3091 		rcu_read_unlock();
3092 		put_task_struct(task);
3093 	}
3094 	if (!ns)
3095 		goto err;
3096 
3097 	if (file->f_mode & FMODE_WRITE) {
3098 		ret = -EACCES;
3099 		if (!ns_capable(ns, CAP_SYS_ADMIN))
3100 			goto err_put_ns;
3101 	}
3102 
3103 	ret = single_open(file, &proc_setgroups_show, ns);
3104 	if (ret)
3105 		goto err_put_ns;
3106 
3107 	return 0;
3108 err_put_ns:
3109 	put_user_ns(ns);
3110 err:
3111 	return ret;
3112 }
3113 
proc_setgroups_release(struct inode * inode,struct file * file)3114 static int proc_setgroups_release(struct inode *inode, struct file *file)
3115 {
3116 	struct seq_file *seq = file->private_data;
3117 	struct user_namespace *ns = seq->private;
3118 	int ret = single_release(inode, file);
3119 	put_user_ns(ns);
3120 	return ret;
3121 }
3122 
3123 static const struct file_operations proc_setgroups_operations = {
3124 	.open		= proc_setgroups_open,
3125 	.write		= proc_setgroups_write,
3126 	.read		= seq_read,
3127 	.llseek		= seq_lseek,
3128 	.release	= proc_setgroups_release,
3129 };
3130 #endif /* CONFIG_USER_NS */
3131 
proc_pid_personality(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)3132 static int proc_pid_personality(struct seq_file *m, struct pid_namespace *ns,
3133 				struct pid *pid, struct task_struct *task)
3134 {
3135 	int err = lock_trace(task);
3136 	if (!err) {
3137 		seq_printf(m, "%08x\n", task->personality);
3138 		unlock_trace(task);
3139 	}
3140 	return err;
3141 }
3142 
3143 #ifdef CONFIG_LIVEPATCH
proc_pid_patch_state(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)3144 static int proc_pid_patch_state(struct seq_file *m, struct pid_namespace *ns,
3145 				struct pid *pid, struct task_struct *task)
3146 {
3147 	seq_printf(m, "%d\n", task->patch_state);
3148 	return 0;
3149 }
3150 #endif /* CONFIG_LIVEPATCH */
3151 
3152 #ifdef CONFIG_STACKLEAK_METRICS
proc_stack_depth(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * task)3153 static int proc_stack_depth(struct seq_file *m, struct pid_namespace *ns,
3154 				struct pid *pid, struct task_struct *task)
3155 {
3156 	unsigned long prev_depth = THREAD_SIZE -
3157 				(task->prev_lowest_stack & (THREAD_SIZE - 1));
3158 	unsigned long depth = THREAD_SIZE -
3159 				(task->lowest_stack & (THREAD_SIZE - 1));
3160 
3161 	seq_printf(m, "previous stack depth: %lu\nstack depth: %lu\n",
3162 							prev_depth, depth);
3163 	return 0;
3164 }
3165 #endif /* CONFIG_STACKLEAK_METRICS */
3166 
3167 /*
3168  * Thread groups
3169  */
3170 static const struct file_operations proc_task_operations;
3171 static const struct inode_operations proc_task_inode_operations;
3172 
3173 static const struct pid_entry tgid_base_stuff[] = {
3174 	DIR("task",       S_IRUGO|S_IXUGO, proc_task_inode_operations, proc_task_operations),
3175 	DIR("fd",         S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
3176 	DIR("map_files",  S_IRUSR|S_IXUSR, proc_map_files_inode_operations, proc_map_files_operations),
3177 	DIR("fdinfo",     S_IRUGO|S_IXUGO, proc_fdinfo_inode_operations, proc_fdinfo_operations),
3178 	DIR("ns",	  S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
3179 #ifdef CONFIG_NET
3180 	DIR("net",        S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
3181 #endif
3182 	REG("environ",    S_IRUSR, proc_environ_operations),
3183 	REG("auxv",       S_IRUSR, proc_auxv_operations),
3184 	ONE("status",     S_IRUGO, proc_pid_status),
3185 	ONE("personality", S_IRUSR, proc_pid_personality),
3186 	ONE("limits",	  S_IRUGO, proc_pid_limits),
3187 #ifdef CONFIG_SCHED_DEBUG
3188 	REG("sched",      S_IRUGO|S_IWUSR, proc_pid_sched_operations),
3189 #endif
3190 #ifdef CONFIG_SCHED_AUTOGROUP
3191 	REG("autogroup",  S_IRUGO|S_IWUSR, proc_pid_sched_autogroup_operations),
3192 #endif
3193 #ifdef CONFIG_TIME_NS
3194 	REG("timens_offsets",  S_IRUGO|S_IWUSR, proc_timens_offsets_operations),
3195 #endif
3196 	REG("comm",      S_IRUGO|S_IWUSR, proc_pid_set_comm_operations),
3197 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
3198 	ONE("syscall",    S_IRUSR, proc_pid_syscall),
3199 #endif
3200 	REG("cmdline",    S_IRUGO, proc_pid_cmdline_ops),
3201 	ONE("stat",       S_IRUGO, proc_tgid_stat),
3202 	ONE("statm",      S_IRUGO, proc_pid_statm),
3203 	REG("maps",       S_IRUGO, proc_pid_maps_operations),
3204 #ifdef CONFIG_NUMA
3205 	REG("numa_maps",  S_IRUGO, proc_pid_numa_maps_operations),
3206 #endif
3207 	REG("mem",        S_IRUSR|S_IWUSR, proc_mem_operations),
3208 	LNK("cwd",        proc_cwd_link),
3209 	LNK("root",       proc_root_link),
3210 	LNK("exe",        proc_exe_link),
3211 	REG("mounts",     S_IRUGO, proc_mounts_operations),
3212 	REG("mountinfo",  S_IRUGO, proc_mountinfo_operations),
3213 	REG("mountstats", S_IRUSR, proc_mountstats_operations),
3214 #ifdef CONFIG_PROC_PAGE_MONITOR
3215 	REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
3216 	REG("smaps",      S_IRUGO, proc_pid_smaps_operations),
3217 	REG("smaps_rollup", S_IRUGO, proc_pid_smaps_rollup_operations),
3218 	REG("pagemap",    S_IRUSR, proc_pagemap_operations),
3219 #endif
3220 #ifdef CONFIG_SECURITY
3221 	DIR("attr",       S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
3222 #endif
3223 #ifdef CONFIG_KALLSYMS
3224 	ONE("wchan",      S_IRUGO, proc_pid_wchan),
3225 #endif
3226 #ifdef CONFIG_STACKTRACE
3227 	ONE("stack",      S_IRUSR, proc_pid_stack),
3228 #endif
3229 #ifdef CONFIG_SCHED_INFO
3230 	ONE("schedstat",  S_IRUGO, proc_pid_schedstat),
3231 #endif
3232 #ifdef CONFIG_LATENCYTOP
3233 	REG("latency",  S_IRUGO, proc_lstats_operations),
3234 #endif
3235 #ifdef CONFIG_PROC_PID_CPUSET
3236 	ONE("cpuset",     S_IRUGO, proc_cpuset_show),
3237 #endif
3238 #ifdef CONFIG_CGROUPS
3239 	ONE("cgroup",  S_IRUGO, proc_cgroup_show),
3240 #endif
3241 #ifdef CONFIG_PROC_CPU_RESCTRL
3242 	ONE("cpu_resctrl_groups", S_IRUGO, proc_resctrl_show),
3243 #endif
3244 	ONE("oom_score",  S_IRUGO, proc_oom_score),
3245 	REG("oom_adj",    S_IRUGO|S_IWUSR, proc_oom_adj_operations),
3246 	REG("oom_score_adj", S_IRUGO|S_IWUSR, proc_oom_score_adj_operations),
3247 #ifdef CONFIG_AUDIT
3248 	REG("loginuid",   S_IWUSR|S_IRUGO, proc_loginuid_operations),
3249 	REG("sessionid",  S_IRUGO, proc_sessionid_operations),
3250 #endif
3251 #ifdef CONFIG_FAULT_INJECTION
3252 	REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
3253 	REG("fail-nth", 0644, proc_fail_nth_operations),
3254 #endif
3255 #ifdef CONFIG_ELF_CORE
3256 	REG("coredump_filter", S_IRUGO|S_IWUSR, proc_coredump_filter_operations),
3257 #endif
3258 #ifdef CONFIG_TASK_IO_ACCOUNTING
3259 	ONE("io",	S_IRUSR, proc_tgid_io_accounting),
3260 #endif
3261 #ifdef CONFIG_USER_NS
3262 	REG("uid_map",    S_IRUGO|S_IWUSR, proc_uid_map_operations),
3263 	REG("gid_map",    S_IRUGO|S_IWUSR, proc_gid_map_operations),
3264 	REG("projid_map", S_IRUGO|S_IWUSR, proc_projid_map_operations),
3265 	REG("setgroups",  S_IRUGO|S_IWUSR, proc_setgroups_operations),
3266 #endif
3267 #if defined(CONFIG_CHECKPOINT_RESTORE) && defined(CONFIG_POSIX_TIMERS)
3268 	REG("timers",	  S_IRUGO, proc_timers_operations),
3269 #endif
3270 	REG("timerslack_ns", S_IRUGO|S_IWUGO, proc_pid_set_timerslack_ns_operations),
3271 #ifdef CONFIG_LIVEPATCH
3272 	ONE("patch_state",  S_IRUSR, proc_pid_patch_state),
3273 #endif
3274 #ifdef CONFIG_CPU_FREQ_TIMES
3275 	ONE("time_in_state", 0444, proc_time_in_state_show),
3276 #endif
3277 #ifdef CONFIG_STACKLEAK_METRICS
3278 	ONE("stack_depth", S_IRUGO, proc_stack_depth),
3279 #endif
3280 #ifdef CONFIG_PROC_PID_ARCH_STATUS
3281 	ONE("arch_status", S_IRUGO, proc_pid_arch_status),
3282 #endif
3283 };
3284 
proc_tgid_base_readdir(struct file * file,struct dir_context * ctx)3285 static int proc_tgid_base_readdir(struct file *file, struct dir_context *ctx)
3286 {
3287 	return proc_pident_readdir(file, ctx,
3288 				   tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff));
3289 }
3290 
3291 static const struct file_operations proc_tgid_base_operations = {
3292 	.read		= generic_read_dir,
3293 	.iterate_shared	= proc_tgid_base_readdir,
3294 	.llseek		= generic_file_llseek,
3295 };
3296 
tgid_pidfd_to_pid(const struct file * file)3297 struct pid *tgid_pidfd_to_pid(const struct file *file)
3298 {
3299 	if (file->f_op != &proc_tgid_base_operations)
3300 		return ERR_PTR(-EBADF);
3301 
3302 	return proc_pid(file_inode(file));
3303 }
3304 
proc_tgid_base_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)3305 static struct dentry *proc_tgid_base_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
3306 {
3307 	return proc_pident_lookup(dir, dentry,
3308 				  tgid_base_stuff,
3309 				  tgid_base_stuff + ARRAY_SIZE(tgid_base_stuff));
3310 }
3311 
3312 static const struct inode_operations proc_tgid_base_inode_operations = {
3313 	.lookup		= proc_tgid_base_lookup,
3314 	.getattr	= pid_getattr,
3315 	.setattr	= proc_setattr,
3316 	.permission	= proc_pid_permission,
3317 };
3318 
3319 /**
3320  * proc_flush_pid -  Remove dcache entries for @pid from the /proc dcache.
3321  * @pid: pid that should be flushed.
3322  *
3323  * This function walks a list of inodes (that belong to any proc
3324  * filesystem) that are attached to the pid and flushes them from
3325  * the dentry cache.
3326  *
3327  * It is safe and reasonable to cache /proc entries for a task until
3328  * that task exits.  After that they just clog up the dcache with
3329  * useless entries, possibly causing useful dcache entries to be
3330  * flushed instead.  This routine is provided to flush those useless
3331  * dcache entries when a process is reaped.
3332  *
3333  * NOTE: This routine is just an optimization so it does not guarantee
3334  *       that no dcache entries will exist after a process is reaped
3335  *       it just makes it very unlikely that any will persist.
3336  */
3337 
proc_flush_pid(struct pid * pid)3338 void proc_flush_pid(struct pid *pid)
3339 {
3340 	proc_invalidate_siblings_dcache(&pid->inodes, &pid->lock);
3341 }
3342 
proc_pid_instantiate(struct dentry * dentry,struct task_struct * task,const void * ptr)3343 static struct dentry *proc_pid_instantiate(struct dentry * dentry,
3344 				   struct task_struct *task, const void *ptr)
3345 {
3346 	struct inode *inode;
3347 
3348 	inode = proc_pid_make_inode(dentry->d_sb, task, S_IFDIR | S_IRUGO | S_IXUGO);
3349 	if (!inode)
3350 		return ERR_PTR(-ENOENT);
3351 
3352 	inode->i_op = &proc_tgid_base_inode_operations;
3353 	inode->i_fop = &proc_tgid_base_operations;
3354 	inode->i_flags|=S_IMMUTABLE;
3355 
3356 	set_nlink(inode, nlink_tgid);
3357 	pid_update_inode(task, inode);
3358 
3359 	d_set_d_op(dentry, &pid_dentry_operations);
3360 	return d_splice_alias(inode, dentry);
3361 }
3362 
proc_pid_lookup(struct dentry * dentry,unsigned int flags)3363 struct dentry *proc_pid_lookup(struct dentry *dentry, unsigned int flags)
3364 {
3365 	struct task_struct *task;
3366 	unsigned tgid;
3367 	struct proc_fs_info *fs_info;
3368 	struct pid_namespace *ns;
3369 	struct dentry *result = ERR_PTR(-ENOENT);
3370 
3371 	tgid = name_to_int(&dentry->d_name);
3372 	if (tgid == ~0U)
3373 		goto out;
3374 
3375 	fs_info = proc_sb_info(dentry->d_sb);
3376 	ns = fs_info->pid_ns;
3377 	rcu_read_lock();
3378 	task = find_task_by_pid_ns(tgid, ns);
3379 	if (task)
3380 		get_task_struct(task);
3381 	rcu_read_unlock();
3382 	if (!task)
3383 		goto out;
3384 
3385 	/* Limit procfs to only ptraceable tasks */
3386 	if (fs_info->hide_pid == HIDEPID_NOT_PTRACEABLE) {
3387 		if (!has_pid_permissions(fs_info, task, HIDEPID_NO_ACCESS))
3388 			goto out_put_task;
3389 	}
3390 
3391 	result = proc_pid_instantiate(dentry, task, NULL);
3392 out_put_task:
3393 	put_task_struct(task);
3394 out:
3395 	return result;
3396 }
3397 
3398 /*
3399  * Find the first task with tgid >= tgid
3400  *
3401  */
3402 struct tgid_iter {
3403 	unsigned int tgid;
3404 	struct task_struct *task;
3405 };
next_tgid(struct pid_namespace * ns,struct tgid_iter iter)3406 static struct tgid_iter next_tgid(struct pid_namespace *ns, struct tgid_iter iter)
3407 {
3408 	struct pid *pid;
3409 
3410 	if (iter.task)
3411 		put_task_struct(iter.task);
3412 	rcu_read_lock();
3413 retry:
3414 	iter.task = NULL;
3415 	pid = find_ge_pid(iter.tgid, ns);
3416 	if (pid) {
3417 		iter.tgid = pid_nr_ns(pid, ns);
3418 		iter.task = pid_task(pid, PIDTYPE_TGID);
3419 		if (!iter.task) {
3420 			iter.tgid += 1;
3421 			goto retry;
3422 		}
3423 		get_task_struct(iter.task);
3424 	}
3425 	rcu_read_unlock();
3426 	return iter;
3427 }
3428 
3429 #define TGID_OFFSET (FIRST_PROCESS_ENTRY + 2)
3430 
3431 /* for the /proc/ directory itself, after non-process stuff has been done */
proc_pid_readdir(struct file * file,struct dir_context * ctx)3432 int proc_pid_readdir(struct file *file, struct dir_context *ctx)
3433 {
3434 	struct tgid_iter iter;
3435 	struct proc_fs_info *fs_info = proc_sb_info(file_inode(file)->i_sb);
3436 	struct pid_namespace *ns = proc_pid_ns(file_inode(file)->i_sb);
3437 	loff_t pos = ctx->pos;
3438 
3439 	if (pos >= PID_MAX_LIMIT + TGID_OFFSET)
3440 		return 0;
3441 
3442 	if (pos == TGID_OFFSET - 2) {
3443 		struct inode *inode = d_inode(fs_info->proc_self);
3444 		if (!dir_emit(ctx, "self", 4, inode->i_ino, DT_LNK))
3445 			return 0;
3446 		ctx->pos = pos = pos + 1;
3447 	}
3448 	if (pos == TGID_OFFSET - 1) {
3449 		struct inode *inode = d_inode(fs_info->proc_thread_self);
3450 		if (!dir_emit(ctx, "thread-self", 11, inode->i_ino, DT_LNK))
3451 			return 0;
3452 		ctx->pos = pos = pos + 1;
3453 	}
3454 	iter.tgid = pos - TGID_OFFSET;
3455 	iter.task = NULL;
3456 	for (iter = next_tgid(ns, iter);
3457 	     iter.task;
3458 	     iter.tgid += 1, iter = next_tgid(ns, iter)) {
3459 		char name[10 + 1];
3460 		unsigned int len;
3461 
3462 		cond_resched();
3463 		if (!has_pid_permissions(fs_info, iter.task, HIDEPID_INVISIBLE))
3464 			continue;
3465 
3466 		len = snprintf(name, sizeof(name), "%u", iter.tgid);
3467 		ctx->pos = iter.tgid + TGID_OFFSET;
3468 		if (!proc_fill_cache(file, ctx, name, len,
3469 				     proc_pid_instantiate, iter.task, NULL)) {
3470 			put_task_struct(iter.task);
3471 			return 0;
3472 		}
3473 	}
3474 	ctx->pos = PID_MAX_LIMIT + TGID_OFFSET;
3475 	return 0;
3476 }
3477 
3478 /*
3479  * proc_tid_comm_permission is a special permission function exclusively
3480  * used for the node /proc/<pid>/task/<tid>/comm.
3481  * It bypasses generic permission checks in the case where a task of the same
3482  * task group attempts to access the node.
3483  * The rationale behind this is that glibc and bionic access this node for
3484  * cross thread naming (pthread_set/getname_np(!self)). However, if
3485  * PR_SET_DUMPABLE gets set to 0 this node among others becomes uid=0 gid=0,
3486  * which locks out the cross thread naming implementation.
3487  * This function makes sure that the node is always accessible for members of
3488  * same thread group.
3489  */
proc_tid_comm_permission(struct inode * inode,int mask)3490 static int proc_tid_comm_permission(struct inode *inode, int mask)
3491 {
3492 	bool is_same_tgroup;
3493 	struct task_struct *task;
3494 
3495 	task = get_proc_task(inode);
3496 	if (!task)
3497 		return -ESRCH;
3498 	is_same_tgroup = same_thread_group(current, task);
3499 	put_task_struct(task);
3500 
3501 	if (likely(is_same_tgroup && !(mask & MAY_EXEC))) {
3502 		/* This file (/proc/<pid>/task/<tid>/comm) can always be
3503 		 * read or written by the members of the corresponding
3504 		 * thread group.
3505 		 */
3506 		return 0;
3507 	}
3508 
3509 	return generic_permission(inode, mask);
3510 }
3511 
3512 static const struct inode_operations proc_tid_comm_inode_operations = {
3513 		.permission = proc_tid_comm_permission,
3514 };
3515 
3516 /*
3517  * Tasks
3518  */
3519 static const struct pid_entry tid_base_stuff[] = {
3520 	DIR("fd",        S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
3521 	DIR("fdinfo",    S_IRUGO|S_IXUGO, proc_fdinfo_inode_operations, proc_fdinfo_operations),
3522 	DIR("ns",	 S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
3523 #ifdef CONFIG_NET
3524 	DIR("net",        S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
3525 #endif
3526 	REG("environ",   S_IRUSR, proc_environ_operations),
3527 	REG("auxv",      S_IRUSR, proc_auxv_operations),
3528 	ONE("status",    S_IRUGO, proc_pid_status),
3529 	ONE("personality", S_IRUSR, proc_pid_personality),
3530 	ONE("limits",	 S_IRUGO, proc_pid_limits),
3531 #ifdef CONFIG_SCHED_DEBUG
3532 	REG("sched",     S_IRUGO|S_IWUSR, proc_pid_sched_operations),
3533 #endif
3534 	NOD("comm",      S_IFREG|S_IRUGO|S_IWUSR,
3535 			 &proc_tid_comm_inode_operations,
3536 			 &proc_pid_set_comm_operations, {}),
3537 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
3538 	ONE("syscall",   S_IRUSR, proc_pid_syscall),
3539 #endif
3540 	REG("cmdline",   S_IRUGO, proc_pid_cmdline_ops),
3541 	ONE("stat",      S_IRUGO, proc_tid_stat),
3542 	ONE("statm",     S_IRUGO, proc_pid_statm),
3543 	REG("maps",      S_IRUGO, proc_pid_maps_operations),
3544 #ifdef CONFIG_PROC_CHILDREN
3545 	REG("children",  S_IRUGO, proc_tid_children_operations),
3546 #endif
3547 #ifdef CONFIG_NUMA
3548 	REG("numa_maps", S_IRUGO, proc_pid_numa_maps_operations),
3549 #endif
3550 	REG("mem",       S_IRUSR|S_IWUSR, proc_mem_operations),
3551 	LNK("cwd",       proc_cwd_link),
3552 	LNK("root",      proc_root_link),
3553 	LNK("exe",       proc_exe_link),
3554 	REG("mounts",    S_IRUGO, proc_mounts_operations),
3555 	REG("mountinfo",  S_IRUGO, proc_mountinfo_operations),
3556 #ifdef CONFIG_PROC_PAGE_MONITOR
3557 	REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
3558 	REG("smaps",     S_IRUGO, proc_pid_smaps_operations),
3559 	REG("smaps_rollup", S_IRUGO, proc_pid_smaps_rollup_operations),
3560 	REG("pagemap",    S_IRUSR, proc_pagemap_operations),
3561 #endif
3562 #ifdef CONFIG_SECURITY
3563 	DIR("attr",      S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
3564 #endif
3565 #ifdef CONFIG_KALLSYMS
3566 	ONE("wchan",     S_IRUGO, proc_pid_wchan),
3567 #endif
3568 #ifdef CONFIG_STACKTRACE
3569 	ONE("stack",      S_IRUSR, proc_pid_stack),
3570 #endif
3571 #ifdef CONFIG_SCHED_INFO
3572 	ONE("schedstat", S_IRUGO, proc_pid_schedstat),
3573 #endif
3574 #ifdef CONFIG_LATENCYTOP
3575 	REG("latency",  S_IRUGO, proc_lstats_operations),
3576 #endif
3577 #ifdef CONFIG_PROC_PID_CPUSET
3578 	ONE("cpuset",    S_IRUGO, proc_cpuset_show),
3579 #endif
3580 #ifdef CONFIG_CGROUPS
3581 	ONE("cgroup",  S_IRUGO, proc_cgroup_show),
3582 #endif
3583 #ifdef CONFIG_PROC_CPU_RESCTRL
3584 	ONE("cpu_resctrl_groups", S_IRUGO, proc_resctrl_show),
3585 #endif
3586 	ONE("oom_score", S_IRUGO, proc_oom_score),
3587 	REG("oom_adj",   S_IRUGO|S_IWUSR, proc_oom_adj_operations),
3588 	REG("oom_score_adj", S_IRUGO|S_IWUSR, proc_oom_score_adj_operations),
3589 #ifdef CONFIG_AUDIT
3590 	REG("loginuid",  S_IWUSR|S_IRUGO, proc_loginuid_operations),
3591 	REG("sessionid",  S_IRUGO, proc_sessionid_operations),
3592 #endif
3593 #ifdef CONFIG_FAULT_INJECTION
3594 	REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
3595 	REG("fail-nth", 0644, proc_fail_nth_operations),
3596 #endif
3597 #ifdef CONFIG_TASK_IO_ACCOUNTING
3598 	ONE("io",	S_IRUSR, proc_tid_io_accounting),
3599 #endif
3600 #ifdef CONFIG_USER_NS
3601 	REG("uid_map",    S_IRUGO|S_IWUSR, proc_uid_map_operations),
3602 	REG("gid_map",    S_IRUGO|S_IWUSR, proc_gid_map_operations),
3603 	REG("projid_map", S_IRUGO|S_IWUSR, proc_projid_map_operations),
3604 	REG("setgroups",  S_IRUGO|S_IWUSR, proc_setgroups_operations),
3605 #endif
3606 #ifdef CONFIG_LIVEPATCH
3607 	ONE("patch_state",  S_IRUSR, proc_pid_patch_state),
3608 #endif
3609 #ifdef CONFIG_PROC_PID_ARCH_STATUS
3610 	ONE("arch_status", S_IRUGO, proc_pid_arch_status),
3611 #endif
3612 #ifdef CONFIG_CPU_FREQ_TIMES
3613 	ONE("time_in_state", 0444, proc_time_in_state_show),
3614 #endif
3615 };
3616 
proc_tid_base_readdir(struct file * file,struct dir_context * ctx)3617 static int proc_tid_base_readdir(struct file *file, struct dir_context *ctx)
3618 {
3619 	return proc_pident_readdir(file, ctx,
3620 				   tid_base_stuff, ARRAY_SIZE(tid_base_stuff));
3621 }
3622 
proc_tid_base_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)3623 static struct dentry *proc_tid_base_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
3624 {
3625 	return proc_pident_lookup(dir, dentry,
3626 				  tid_base_stuff,
3627 				  tid_base_stuff + ARRAY_SIZE(tid_base_stuff));
3628 }
3629 
3630 static const struct file_operations proc_tid_base_operations = {
3631 	.read		= generic_read_dir,
3632 	.iterate_shared	= proc_tid_base_readdir,
3633 	.llseek		= generic_file_llseek,
3634 };
3635 
3636 static const struct inode_operations proc_tid_base_inode_operations = {
3637 	.lookup		= proc_tid_base_lookup,
3638 	.getattr	= pid_getattr,
3639 	.setattr	= proc_setattr,
3640 };
3641 
proc_task_instantiate(struct dentry * dentry,struct task_struct * task,const void * ptr)3642 static struct dentry *proc_task_instantiate(struct dentry *dentry,
3643 	struct task_struct *task, const void *ptr)
3644 {
3645 	struct inode *inode;
3646 	inode = proc_pid_make_inode(dentry->d_sb, task, S_IFDIR | S_IRUGO | S_IXUGO);
3647 	if (!inode)
3648 		return ERR_PTR(-ENOENT);
3649 
3650 	inode->i_op = &proc_tid_base_inode_operations;
3651 	inode->i_fop = &proc_tid_base_operations;
3652 	inode->i_flags |= S_IMMUTABLE;
3653 
3654 	set_nlink(inode, nlink_tid);
3655 	pid_update_inode(task, inode);
3656 
3657 	d_set_d_op(dentry, &pid_dentry_operations);
3658 	return d_splice_alias(inode, dentry);
3659 }
3660 
proc_task_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)3661 static struct dentry *proc_task_lookup(struct inode *dir, struct dentry * dentry, unsigned int flags)
3662 {
3663 	struct task_struct *task;
3664 	struct task_struct *leader = get_proc_task(dir);
3665 	unsigned tid;
3666 	struct proc_fs_info *fs_info;
3667 	struct pid_namespace *ns;
3668 	struct dentry *result = ERR_PTR(-ENOENT);
3669 
3670 	if (!leader)
3671 		goto out_no_task;
3672 
3673 	tid = name_to_int(&dentry->d_name);
3674 	if (tid == ~0U)
3675 		goto out;
3676 
3677 	fs_info = proc_sb_info(dentry->d_sb);
3678 	ns = fs_info->pid_ns;
3679 	rcu_read_lock();
3680 	task = find_task_by_pid_ns(tid, ns);
3681 	if (task)
3682 		get_task_struct(task);
3683 	rcu_read_unlock();
3684 	if (!task)
3685 		goto out;
3686 	if (!same_thread_group(leader, task))
3687 		goto out_drop_task;
3688 
3689 	result = proc_task_instantiate(dentry, task, NULL);
3690 out_drop_task:
3691 	put_task_struct(task);
3692 out:
3693 	put_task_struct(leader);
3694 out_no_task:
3695 	return result;
3696 }
3697 
3698 /*
3699  * Find the first tid of a thread group to return to user space.
3700  *
3701  * Usually this is just the thread group leader, but if the users
3702  * buffer was too small or there was a seek into the middle of the
3703  * directory we have more work todo.
3704  *
3705  * In the case of a short read we start with find_task_by_pid.
3706  *
3707  * In the case of a seek we start with the leader and walk nr
3708  * threads past it.
3709  */
first_tid(struct pid * pid,int tid,loff_t f_pos,struct pid_namespace * ns)3710 static struct task_struct *first_tid(struct pid *pid, int tid, loff_t f_pos,
3711 					struct pid_namespace *ns)
3712 {
3713 	struct task_struct *pos, *task;
3714 	unsigned long nr = f_pos;
3715 
3716 	if (nr != f_pos)	/* 32bit overflow? */
3717 		return NULL;
3718 
3719 	rcu_read_lock();
3720 	task = pid_task(pid, PIDTYPE_PID);
3721 	if (!task)
3722 		goto fail;
3723 
3724 	/* Attempt to start with the tid of a thread */
3725 	if (tid && nr) {
3726 		pos = find_task_by_pid_ns(tid, ns);
3727 		if (pos && same_thread_group(pos, task))
3728 			goto found;
3729 	}
3730 
3731 	/* If nr exceeds the number of threads there is nothing todo */
3732 	if (nr >= get_nr_threads(task))
3733 		goto fail;
3734 
3735 	/* If we haven't found our starting place yet start
3736 	 * with the leader and walk nr threads forward.
3737 	 */
3738 	pos = task = task->group_leader;
3739 	do {
3740 		if (!nr--)
3741 			goto found;
3742 	} while_each_thread(task, pos);
3743 fail:
3744 	pos = NULL;
3745 	goto out;
3746 found:
3747 	get_task_struct(pos);
3748 out:
3749 	rcu_read_unlock();
3750 	return pos;
3751 }
3752 
3753 /*
3754  * Find the next thread in the thread list.
3755  * Return NULL if there is an error or no next thread.
3756  *
3757  * The reference to the input task_struct is released.
3758  */
next_tid(struct task_struct * start)3759 static struct task_struct *next_tid(struct task_struct *start)
3760 {
3761 	struct task_struct *pos = NULL;
3762 	rcu_read_lock();
3763 	if (pid_alive(start)) {
3764 		pos = next_thread(start);
3765 		if (thread_group_leader(pos))
3766 			pos = NULL;
3767 		else
3768 			get_task_struct(pos);
3769 	}
3770 	rcu_read_unlock();
3771 	put_task_struct(start);
3772 	return pos;
3773 }
3774 
3775 /* for the /proc/TGID/task/ directories */
proc_task_readdir(struct file * file,struct dir_context * ctx)3776 static int proc_task_readdir(struct file *file, struct dir_context *ctx)
3777 {
3778 	struct inode *inode = file_inode(file);
3779 	struct task_struct *task;
3780 	struct pid_namespace *ns;
3781 	int tid;
3782 
3783 	if (proc_inode_is_dead(inode))
3784 		return -ENOENT;
3785 
3786 	if (!dir_emit_dots(file, ctx))
3787 		return 0;
3788 
3789 	/* f_version caches the tgid value that the last readdir call couldn't
3790 	 * return. lseek aka telldir automagically resets f_version to 0.
3791 	 */
3792 	ns = proc_pid_ns(inode->i_sb);
3793 	tid = (int)file->f_version;
3794 	file->f_version = 0;
3795 	for (task = first_tid(proc_pid(inode), tid, ctx->pos - 2, ns);
3796 	     task;
3797 	     task = next_tid(task), ctx->pos++) {
3798 		char name[10 + 1];
3799 		unsigned int len;
3800 		tid = task_pid_nr_ns(task, ns);
3801 		len = snprintf(name, sizeof(name), "%u", tid);
3802 		if (!proc_fill_cache(file, ctx, name, len,
3803 				proc_task_instantiate, task, NULL)) {
3804 			/* returning this tgid failed, save it as the first
3805 			 * pid for the next readir call */
3806 			file->f_version = (u64)tid;
3807 			put_task_struct(task);
3808 			break;
3809 		}
3810 	}
3811 
3812 	return 0;
3813 }
3814 
proc_task_getattr(const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)3815 static int proc_task_getattr(const struct path *path, struct kstat *stat,
3816 			     u32 request_mask, unsigned int query_flags)
3817 {
3818 	struct inode *inode = d_inode(path->dentry);
3819 	struct task_struct *p = get_proc_task(inode);
3820 	generic_fillattr(inode, stat);
3821 
3822 	if (p) {
3823 		stat->nlink += get_nr_threads(p);
3824 		put_task_struct(p);
3825 	}
3826 
3827 	return 0;
3828 }
3829 
3830 static const struct inode_operations proc_task_inode_operations = {
3831 	.lookup		= proc_task_lookup,
3832 	.getattr	= proc_task_getattr,
3833 	.setattr	= proc_setattr,
3834 	.permission	= proc_pid_permission,
3835 };
3836 
3837 static const struct file_operations proc_task_operations = {
3838 	.read		= generic_read_dir,
3839 	.iterate_shared	= proc_task_readdir,
3840 	.llseek		= generic_file_llseek,
3841 };
3842 
set_proc_pid_nlink(void)3843 void __init set_proc_pid_nlink(void)
3844 {
3845 	nlink_tid = pid_entry_nlink(tid_base_stuff, ARRAY_SIZE(tid_base_stuff));
3846 	nlink_tgid = pid_entry_nlink(tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff));
3847 }
3848