23

How convert char[] to int in linux kernel

with validation that the text entered is actually an int?

int procfile_write(struct file *file, const char *buffer, unsigned long count,
       void *data)
{

   char procfs_buffer[PROCFS_MAX_SIZE];

    /* get buffer size */
   unsigned long procfs_buffer_size = count;
   if (procfs_buffer_size > PROCFS_MAX_SIZE ) {
       procfs_buffer_size = PROCFS_MAX_SIZE;
   }

   /* write data to the buffer */
   if ( copy_from_user(procfs_buffer, buffer, procfs_buffer_size) ) {
       return -EFAULT;
   }

   int = buffer2int(procfs_buffer, procfs_buffer_size);

   return procfs_buffer_size;
}
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
caeycae
  • 1,137
  • 3
  • 12
  • 28
  • 1
    Are you essentially looking for `atoi` with better validation? – forsvarir May 26 '11 at 13:46
  • 7
    the kernel does not have either `atoi` nor `strtol` as such - the "C/C++ standard library" is only available to userspace applications. For many such functions there are functional equivalents in kernel land, though, but not necessarily with the same name. – FrankH. May 26 '11 at 13:56

6 Answers6

37

See the various incarnations of kstrtol() in #include <include/linux/kernel.h> in your friendly linux source tree.

Which one you need depends on whether the *buffer is a user or a kernel address, and on how strict your needs on error handling / checking of the buffer contents are (things like, is 123qx invalid or should it return 123 ?).

FrankH.
  • 17,675
  • 3
  • 44
  • 63
  • Yes, `strict_strtol()` or `simple_strtol()` will probably do the job here. – Eugene May 26 '11 at 14:51
  • 123dew is invalid and i need to check thas a user adderss – caeycae May 26 '11 at 15:12
  • See also https://lkml.org/lkml/2011/4/12/361 regarding the `kstrtol...()` funcs vs. `simple_strtol()` and/or `strict_strtol()`. In any case, you're right if you're not on bleeding edge use those. See that also regarding "user address". – FrankH. May 26 '11 at 15:17
  • It's a mistake. `kstrotox()` are not the replacements for `simple_strtox()` ones. – 0andriy Mar 21 '19 at 14:26
7

Minimal runnable kstrtoull_from_user debugfs example

The kstrto*_from_user family is very convenient when dealing with user data.

kstrto.c:

#include <linux/debugfs.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <uapi/linux/stat.h> /* S_IRUSR */

static struct dentry *toplevel_file;

static ssize_t write(struct file *filp, const char __user *buf, size_t len, loff_t *off)
{
    int ret;
    unsigned long long res;
    ret = kstrtoull_from_user(buf, len, 10, &res);
    if (ret) {
        /* Negative error code. */
        pr_info("ko = %d\n", ret);
        return ret;
    } else {
        pr_info("ok = %llu\n", res);
        *off= len;
        return len;
    }
}

static const struct file_operations fops = {
    .owner = THIS_MODULE,
    .write = write,
};

static int myinit(void)
{
    toplevel_file = debugfs_create_file("lkmc_kstrto", S_IWUSR, NULL, NULL, &fops);
    if (!toplevel_file) {
        return -1;
    }
    return 0;
}

static void myexit(void)
{
    debugfs_remove(toplevel_file);
}

module_init(myinit)
module_exit(myexit)
MODULE_LICENSE("GPL");

Usage:

insmod kstrto.ko
cd /sys/kernel/debug
echo 1234 > lkmc_kstrto
echo foobar > lkmc_kstrto

Dmesg outputs:

ok = 1234
ko = -22

Tested in Linux kernel 4.16 with this QEMU + Buildroot setup.

For this particular example, you might have wanted to use debugfs_create_u32 instead.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
1

Because of the unavailability of a lot of common function/macros in linux kernel, you can not use any direct function to get integer value from a string buffer.

This is the code that I have been using for a long time for doing this and it can be used on all *NIX flavors (probably without any modification).

This is the modified form of code, which I used a long time back from an open source project (don't remember the name now).

#define ISSPACE(c)  ((c) == ' ' || ((c) >= '\t' && (c) <= '\r'))
#define ISASCII(c)  (((c) & ~0x7f) == 0)
#define ISUPPER(c)  ((c) >= 'A' && (c) <= 'Z')
#define ISLOWER(c)  ((c) >= 'a' && (c) <= 'z')
#define ISALPHA(c)  (ISUPPER(c) || ISLOWER(c))
#define ISDIGIT(c)  ((c) >= '0' && (c) <= '9')

unsigned long mystr_toul (
    char*   nstr,
    char**  endptr,
    int base)
{
#if !(defined(__KERNEL__))
    return strtoul (nstr, endptr, base);    /* user mode */

#else
    char* s = nstr;
    unsigned long acc;
    unsigned char c;
    unsigned long cutoff;
    int neg = 0, any, cutlim;

    do
    {
        c = *s++;
    } while (ISSPACE(c));

    if (c == '-')
    {
        neg = 1;
        c = *s++;
    }
    else if (c == '+')
        c = *s++;

    if ((base == 0 || base == 16) &&
        c == '0' && (*s == 'x' || *s == 'X'))
    {
        c = s[1];
        s += 2;
        base = 16;
    }
    if (base == 0)
        base = c == '0' ? 8 : 10;

    cutoff = (unsigned long)ULONG_MAX / (unsigned long)base;
    cutlim = (unsigned long)ULONG_MAX % (unsigned long)base;
    for (acc = 0, any = 0; ; c = *s++)
    {
        if (!ISASCII(c))
            break;
        if (ISDIGIT(c))
            c -= '0';
        else if (ISALPHA(c))
            c -= ISUPPER(c) ? 'A' - 10 : 'a' - 10;
        else
            break;

        if (c >= base)
            break;
        if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
            any = -1;
        else
        {
            any = 1;
            acc *= base;
            acc += c;
        }
    }

    if (any < 0)
    {
        acc = INT_MAX;
    }
    else if (neg)
        acc = -acc;
    if (endptr != 0)
        *((const char **)endptr) = any ? s - 1 : nstr;
    return (acc);
#endif
}
forsvarir
  • 10,749
  • 6
  • 46
  • 77
Vikram.exe
  • 4,565
  • 3
  • 29
  • 40
  • 2
    Portability is ok but reimplementation is hardly the best thing for kernel code; when you talk "other UNIXes" then e.g. the Solaris kernel _does_ have `strtol()` (even documented in the Solaris section 9 manpages, so does FreeBSD (it's in libkern). Linux has it though named differently. On all of these, a `#define` would do ... – FrankH. May 26 '11 at 14:24
  • @FrankH, Agreed. but I am sure, if your code is to be shipped on a lot of os's (like the 1 I am working on), you will surely find atleast 1 that doesn't support/has implemented the required function. Anyways, I totally agree that its always better to use an existing code instead of using your own in such places. – Vikram.exe May 26 '11 at 14:36
  • This is just flat out wrong. As the other answer says, Linux does have very usable functions for converting strings to integers. – Roland May 26 '11 at 21:15
  • @Roland Just because an accepted answer says so doesn't mean that that is correct. Please read my second comment on this post, hope that will clear your doubt. And I seriously couldn't think of a reason for the down vote. – Vikram.exe May 27 '11 at 07:09
  • The question relates to the linux kernel. Other kernels? who cares. – hookenz Aug 22 '12 at 03:43
0

You could use strtoul or strtol. Here's a link to the man pages:

http://www.kernel.org/doc/man-pages/online/pages/man3/strtoul.3.html
http://www.kernel.org/doc/man-pages/online/pages/man3/strtol.3.html

Bhargav
  • 9,869
  • 1
  • 19
  • 29
  • 2
    AFAIK, you can not use them directly in kernel mode and even if it is available in some form in some kernel, this is not guaranteed to work on all *NIX platforms for sure. – Vikram.exe May 26 '11 at 14:06
  • @Vikram: I wasn't aware of this constraint. – Bhargav May 26 '11 at 14:23
0

I use sscanf() (the kernel version) to scan from a string stream, and it works on 2.6.39-gentoo-r3. Frankly, I could never get simple_strtol() to work in the kernel--I am currently figuring out why this doesn't work on my box.

  ...
  memcpy(bufActual, calc_buffer, calc_buffer_size);
  /* a = simple_strtol(bufActual, NULL, 10); */ // Could not get this to work
  sscanf(bufActual, "%c%ld", &opr, &a); // places '+' in opr and a=20 for bufActual = "20+\0"
  ...
Sonny
  • 2,103
  • 1
  • 26
  • 34
-1

Use atoi and isdigit (note isdigit just takes a char). http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

Blazes
  • 4,721
  • 2
  • 22
  • 29