xref: /linux/fs/proc/self.c (revision ca55b2fef3a9373fcfc30f82fd26bc7fccbda732)
1 #include <linux/sched.h>
2 #include <linux/slab.h>
3 #include <linux/pid_namespace.h>
4 #include "internal.h"
5 
6 /*
7  * /proc/self:
8  */
9 static int proc_self_readlink(struct dentry *dentry, char __user *buffer,
10 			      int buflen)
11 {
12 	struct pid_namespace *ns = dentry->d_sb->s_fs_info;
13 	pid_t tgid = task_tgid_nr_ns(current, ns);
14 	char tmp[PROC_NUMBUF];
15 	if (!tgid)
16 		return -ENOENT;
17 	sprintf(tmp, "%d", tgid);
18 	return readlink_copy(buffer, buflen, tmp);
19 }
20 
21 static const char *proc_self_follow_link(struct dentry *dentry, void **cookie)
22 {
23 	struct pid_namespace *ns = dentry->d_sb->s_fs_info;
24 	pid_t tgid = task_tgid_nr_ns(current, ns);
25 	char *name;
26 
27 	if (!tgid)
28 		return ERR_PTR(-ENOENT);
29 	/* 11 for max length of signed int in decimal + NULL term */
30 	name = kmalloc(12, GFP_KERNEL);
31 	if (!name)
32 		return ERR_PTR(-ENOMEM);
33 	sprintf(name, "%d", tgid);
34 	return *cookie = name;
35 }
36 
37 static const struct inode_operations proc_self_inode_operations = {
38 	.readlink	= proc_self_readlink,
39 	.follow_link	= proc_self_follow_link,
40 	.put_link	= kfree_put_link,
41 };
42 
43 static unsigned self_inum;
44 
45 int proc_setup_self(struct super_block *s)
46 {
47 	struct inode *root_inode = d_inode(s->s_root);
48 	struct pid_namespace *ns = s->s_fs_info;
49 	struct dentry *self;
50 
51 	mutex_lock(&root_inode->i_mutex);
52 	self = d_alloc_name(s->s_root, "self");
53 	if (self) {
54 		struct inode *inode = new_inode_pseudo(s);
55 		if (inode) {
56 			inode->i_ino = self_inum;
57 			inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
58 			inode->i_mode = S_IFLNK | S_IRWXUGO;
59 			inode->i_uid = GLOBAL_ROOT_UID;
60 			inode->i_gid = GLOBAL_ROOT_GID;
61 			inode->i_op = &proc_self_inode_operations;
62 			d_add(self, inode);
63 		} else {
64 			dput(self);
65 			self = ERR_PTR(-ENOMEM);
66 		}
67 	} else {
68 		self = ERR_PTR(-ENOMEM);
69 	}
70 	mutex_unlock(&root_inode->i_mutex);
71 	if (IS_ERR(self)) {
72 		pr_err("proc_fill_super: can't allocate /proc/self\n");
73 		return PTR_ERR(self);
74 	}
75 	ns->proc_self = self;
76 	return 0;
77 }
78 
79 void __init proc_self_init(void)
80 {
81 	proc_alloc_inum(&self_inum);
82 }
83