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