</>EmbeddedInterview

Why use copy_to_user and copy_from_user instead of memcpy?

MediumLinux Kernel & Device Drivers

Short answer: A pointer from user space is untrusted: it may be invalid, point into kernel memory, or refer to a page that is not resident yet. copy_from_user/copy_to_user check that the range is in user space (access_ok), handle page faults safely (returning the number of bytes not copied instead of crashing), and temporarily lift hardware protections such as ARM PAN and x86 SMAP that block the kernel from touching user memory by accident. A plain memcpy could crash the kernel or be used to read or overwrite kernel memory.

if (copy_from_user(&cfg, ubuf, sizeof cfg))
    return -EFAULT;                 /* non-zero return = some bytes failed */

if (put_user(value, (u32 __user *)arg))   /* single values: get_user / put_user */
    return -EFAULT;

Details

  • These functions may sleep (page faults can require reading from disk), so they cannot be called in atomic context or with a spinlock held. Copy into a kernel buffer first, then take the spinlock.
  • The __user annotation marks user pointers; sparse (make C=1) warns when they are dereferenced directly.
  • For strings use strncpy_from_user, or memdup_user / memdup_user_nul to allocate and copy in one step.
  • Double-fetch bugs: reading the same user memory twice (e.g. once to read a length, again to copy) lets another thread change it in between; copy once into kernel memory and validate the copy.
  • Hardening (CONFIG_HARDENED_USERCOPY) checks that kernel objects copied out are within their slab bounds.