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