xref: /linux-6.15/include/linux/uaccess.h (revision 428e2976)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef __LINUX_UACCESS_H__
3 #define __LINUX_UACCESS_H__
4 
5 #include <linux/instrumented.h>
6 #include <linux/sched.h>
7 #include <linux/thread_info.h>
8 
9 #include <asm/uaccess.h>
10 
11 /*
12  * Architectures should provide two primitives (raw_copy_{to,from}_user())
13  * and get rid of their private instances of copy_{to,from}_user() and
14  * __copy_{to,from}_user{,_inatomic}().
15  *
16  * raw_copy_{to,from}_user(to, from, size) should copy up to size bytes and
17  * return the amount left to copy.  They should assume that access_ok() has
18  * already been checked (and succeeded); they should *not* zero-pad anything.
19  * No KASAN or object size checks either - those belong here.
20  *
21  * Both of these functions should attempt to copy size bytes starting at from
22  * into the area starting at to.  They must not fetch or store anything
23  * outside of those areas.  Return value must be between 0 (everything
24  * copied successfully) and size (nothing copied).
25  *
26  * If raw_copy_{to,from}_user(to, from, size) returns N, size - N bytes starting
27  * at to must become equal to the bytes fetched from the corresponding area
28  * starting at from.  All data past to + size - N must be left unmodified.
29  *
30  * If copying succeeds, the return value must be 0.  If some data cannot be
31  * fetched, it is permitted to copy less than had been fetched; the only
32  * hard requirement is that not storing anything at all (i.e. returning size)
33  * should happen only when nothing could be copied.  In other words, you don't
34  * have to squeeze as much as possible - it is allowed, but not necessary.
35  *
36  * For raw_copy_from_user() to always points to kernel memory and no faults
37  * on store should happen.  Interpretation of from is affected by set_fs().
38  * For raw_copy_to_user() it's the other way round.
39  *
40  * Both can be inlined - it's up to architectures whether it wants to bother
41  * with that.  They should not be used directly; they are used to implement
42  * the 6 functions (copy_{to,from}_user(), __copy_{to,from}_user_inatomic())
43  * that are used instead.  Out of those, __... ones are inlined.  Plain
44  * copy_{to,from}_user() might or might not be inlined.  If you want them
45  * inlined, have asm/uaccess.h define INLINE_COPY_{TO,FROM}_USER.
46  *
47  * NOTE: only copy_from_user() zero-pads the destination in case of short copy.
48  * Neither __copy_from_user() nor __copy_from_user_inatomic() zero anything
49  * at all; their callers absolutely must check the return value.
50  *
51  * Biarch ones should also provide raw_copy_in_user() - similar to the above,
52  * but both source and destination are __user pointers (affected by set_fs()
53  * as usual) and both source and destination can trigger faults.
54  */
55 
56 static __always_inline __must_check unsigned long
57 __copy_from_user_inatomic(void *to, const void __user *from, unsigned long n)
58 {
59 	instrument_copy_from_user(to, from, n);
60 	check_object_size(to, n, false);
61 	return raw_copy_from_user(to, from, n);
62 }
63 
64 static __always_inline __must_check unsigned long
65 __copy_from_user(void *to, const void __user *from, unsigned long n)
66 {
67 	might_fault();
68 	instrument_copy_from_user(to, from, n);
69 	check_object_size(to, n, false);
70 	return raw_copy_from_user(to, from, n);
71 }
72 
73 /**
74  * __copy_to_user_inatomic: - Copy a block of data into user space, with less checking.
75  * @to:   Destination address, in user space.
76  * @from: Source address, in kernel space.
77  * @n:    Number of bytes to copy.
78  *
79  * Context: User context only.
80  *
81  * Copy data from kernel space to user space.  Caller must check
82  * the specified block with access_ok() before calling this function.
83  * The caller should also make sure he pins the user space address
84  * so that we don't result in page fault and sleep.
85  */
86 static __always_inline __must_check unsigned long
87 __copy_to_user_inatomic(void __user *to, const void *from, unsigned long n)
88 {
89 	instrument_copy_to_user(to, from, n);
90 	check_object_size(from, n, true);
91 	return raw_copy_to_user(to, from, n);
92 }
93 
94 static __always_inline __must_check unsigned long
95 __copy_to_user(void __user *to, const void *from, unsigned long n)
96 {
97 	might_fault();
98 	instrument_copy_to_user(to, from, n);
99 	check_object_size(from, n, true);
100 	return raw_copy_to_user(to, from, n);
101 }
102 
103 #ifdef INLINE_COPY_FROM_USER
104 static inline __must_check unsigned long
105 _copy_from_user(void *to, const void __user *from, unsigned long n)
106 {
107 	unsigned long res = n;
108 	might_fault();
109 	if (likely(access_ok(from, n))) {
110 		instrument_copy_from_user(to, from, n);
111 		res = raw_copy_from_user(to, from, n);
112 	}
113 	if (unlikely(res))
114 		memset(to + (n - res), 0, res);
115 	return res;
116 }
117 #else
118 extern __must_check unsigned long
119 _copy_from_user(void *, const void __user *, unsigned long);
120 #endif
121 
122 #ifdef INLINE_COPY_TO_USER
123 static inline __must_check unsigned long
124 _copy_to_user(void __user *to, const void *from, unsigned long n)
125 {
126 	might_fault();
127 	if (access_ok(to, n)) {
128 		instrument_copy_to_user(to, from, n);
129 		n = raw_copy_to_user(to, from, n);
130 	}
131 	return n;
132 }
133 #else
134 extern __must_check unsigned long
135 _copy_to_user(void __user *, const void *, unsigned long);
136 #endif
137 
138 static __always_inline unsigned long __must_check
139 copy_from_user(void *to, const void __user *from, unsigned long n)
140 {
141 	if (likely(check_copy_size(to, n, false)))
142 		n = _copy_from_user(to, from, n);
143 	return n;
144 }
145 
146 static __always_inline unsigned long __must_check
147 copy_to_user(void __user *to, const void *from, unsigned long n)
148 {
149 	if (likely(check_copy_size(from, n, true)))
150 		n = _copy_to_user(to, from, n);
151 	return n;
152 }
153 #ifdef CONFIG_COMPAT
154 static __always_inline unsigned long __must_check
155 copy_in_user(void __user *to, const void __user *from, unsigned long n)
156 {
157 	might_fault();
158 	if (access_ok(to, n) && access_ok(from, n))
159 		n = raw_copy_in_user(to, from, n);
160 	return n;
161 }
162 #endif
163 
164 static __always_inline void pagefault_disabled_inc(void)
165 {
166 	current->pagefault_disabled++;
167 }
168 
169 static __always_inline void pagefault_disabled_dec(void)
170 {
171 	current->pagefault_disabled--;
172 }
173 
174 /*
175  * These routines enable/disable the pagefault handler. If disabled, it will
176  * not take any locks and go straight to the fixup table.
177  *
178  * User access methods will not sleep when called from a pagefault_disabled()
179  * environment.
180  */
181 static inline void pagefault_disable(void)
182 {
183 	pagefault_disabled_inc();
184 	/*
185 	 * make sure to have issued the store before a pagefault
186 	 * can hit.
187 	 */
188 	barrier();
189 }
190 
191 static inline void pagefault_enable(void)
192 {
193 	/*
194 	 * make sure to issue those last loads/stores before enabling
195 	 * the pagefault handler again.
196 	 */
197 	barrier();
198 	pagefault_disabled_dec();
199 }
200 
201 /*
202  * Is the pagefault handler disabled? If so, user access methods will not sleep.
203  */
204 static inline bool pagefault_disabled(void)
205 {
206 	return current->pagefault_disabled != 0;
207 }
208 
209 /*
210  * The pagefault handler is in general disabled by pagefault_disable() or
211  * when in irq context (via in_atomic()).
212  *
213  * This function should only be used by the fault handlers. Other users should
214  * stick to pagefault_disabled().
215  * Please NEVER use preempt_disable() to disable the fault handler. With
216  * !CONFIG_PREEMPT_COUNT, this is like a NOP. So the handler won't be disabled.
217  * in_atomic() will report different values based on !CONFIG_PREEMPT_COUNT.
218  */
219 #define faulthandler_disabled() (pagefault_disabled() || in_atomic())
220 
221 #ifndef ARCH_HAS_NOCACHE_UACCESS
222 
223 static inline __must_check unsigned long
224 __copy_from_user_inatomic_nocache(void *to, const void __user *from,
225 				  unsigned long n)
226 {
227 	return __copy_from_user_inatomic(to, from, n);
228 }
229 
230 #endif		/* ARCH_HAS_NOCACHE_UACCESS */
231 
232 extern __must_check int check_zeroed_user(const void __user *from, size_t size);
233 
234 /**
235  * copy_struct_from_user: copy a struct from userspace
236  * @dst:   Destination address, in kernel space. This buffer must be @ksize
237  *         bytes long.
238  * @ksize: Size of @dst struct.
239  * @src:   Source address, in userspace.
240  * @usize: (Alleged) size of @src struct.
241  *
242  * Copies a struct from userspace to kernel space, in a way that guarantees
243  * backwards-compatibility for struct syscall arguments (as long as future
244  * struct extensions are made such that all new fields are *appended* to the
245  * old struct, and zeroed-out new fields have the same meaning as the old
246  * struct).
247  *
248  * @ksize is just sizeof(*dst), and @usize should've been passed by userspace.
249  * The recommended usage is something like the following:
250  *
251  *   SYSCALL_DEFINE2(foobar, const struct foo __user *, uarg, size_t, usize)
252  *   {
253  *      int err;
254  *      struct foo karg = {};
255  *
256  *      if (usize > PAGE_SIZE)
257  *        return -E2BIG;
258  *      if (usize < FOO_SIZE_VER0)
259  *        return -EINVAL;
260  *
261  *      err = copy_struct_from_user(&karg, sizeof(karg), uarg, usize);
262  *      if (err)
263  *        return err;
264  *
265  *      // ...
266  *   }
267  *
268  * There are three cases to consider:
269  *  * If @usize == @ksize, then it's copied verbatim.
270  *  * If @usize < @ksize, then the userspace has passed an old struct to a
271  *    newer kernel. The rest of the trailing bytes in @dst (@ksize - @usize)
272  *    are to be zero-filled.
273  *  * If @usize > @ksize, then the userspace has passed a new struct to an
274  *    older kernel. The trailing bytes unknown to the kernel (@usize - @ksize)
275  *    are checked to ensure they are zeroed, otherwise -E2BIG is returned.
276  *
277  * Returns (in all cases, some data may have been copied):
278  *  * -E2BIG:  (@usize > @ksize) and there are non-zero trailing bytes in @src.
279  *  * -EFAULT: access to userspace failed.
280  */
281 static __always_inline __must_check int
282 copy_struct_from_user(void *dst, size_t ksize, const void __user *src,
283 		      size_t usize)
284 {
285 	size_t size = min(ksize, usize);
286 	size_t rest = max(ksize, usize) - size;
287 
288 	/* Deal with trailing bytes. */
289 	if (usize < ksize) {
290 		memset(dst + size, 0, rest);
291 	} else if (usize > ksize) {
292 		int ret = check_zeroed_user(src + size, rest);
293 		if (ret <= 0)
294 			return ret ?: -E2BIG;
295 	}
296 	/* Copy the interoperable parts of the struct. */
297 	if (copy_from_user(dst, src, size))
298 		return -EFAULT;
299 	return 0;
300 }
301 
302 bool copy_from_kernel_nofault_allowed(const void *unsafe_src, size_t size);
303 
304 long copy_from_kernel_nofault(void *dst, const void *src, size_t size);
305 long notrace copy_to_kernel_nofault(void *dst, const void *src, size_t size);
306 
307 long copy_from_user_nofault(void *dst, const void __user *src, size_t size);
308 long notrace copy_to_user_nofault(void __user *dst, const void *src,
309 		size_t size);
310 
311 long strncpy_from_kernel_nofault(char *dst, const void *unsafe_addr,
312 		long count);
313 
314 long strncpy_from_user_nofault(char *dst, const void __user *unsafe_addr,
315 		long count);
316 long strnlen_user_nofault(const void __user *unsafe_addr, long count);
317 
318 /**
319  * get_kernel_nofault(): safely attempt to read from a location
320  * @val: read into this variable
321  * @ptr: address to read from
322  *
323  * Returns 0 on success, or -EFAULT.
324  */
325 #define get_kernel_nofault(val, ptr) ({				\
326 	const typeof(val) *__gk_ptr = (ptr);			\
327 	copy_from_kernel_nofault(&(val), __gk_ptr, sizeof(val));\
328 })
329 
330 #ifndef user_access_begin
331 #define user_access_begin(ptr,len) access_ok(ptr, len)
332 #define user_access_end() do { } while (0)
333 #define unsafe_op_wrap(op, err) do { if (unlikely(op)) goto err; } while (0)
334 #define unsafe_get_user(x,p,e) unsafe_op_wrap(__get_user(x,p),e)
335 #define unsafe_put_user(x,p,e) unsafe_op_wrap(__put_user(x,p),e)
336 #define unsafe_copy_to_user(d,s,l,e) unsafe_op_wrap(__copy_to_user(d,s,l),e)
337 static inline unsigned long user_access_save(void) { return 0UL; }
338 static inline void user_access_restore(unsigned long flags) { }
339 #endif
340 #ifndef user_write_access_begin
341 #define user_write_access_begin user_access_begin
342 #define user_write_access_end user_access_end
343 #endif
344 #ifndef user_read_access_begin
345 #define user_read_access_begin user_access_begin
346 #define user_read_access_end user_access_end
347 #endif
348 
349 #ifdef CONFIG_HARDENED_USERCOPY
350 void usercopy_warn(const char *name, const char *detail, bool to_user,
351 		   unsigned long offset, unsigned long len);
352 void __noreturn usercopy_abort(const char *name, const char *detail,
353 			       bool to_user, unsigned long offset,
354 			       unsigned long len);
355 #endif
356 
357 #endif		/* __LINUX_UACCESS_H__ */
358