Linux内核中如何将char[]字符串转换为int?

发布于 2024-11-10 04:33:09 字数 619 浏览 3 评论 0原文

如何在linux内核中将char[]转换为int

并验证输入的文本实际上是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;
}

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

美煞众生 2024-11-17 04:33:09

请参阅 #include在您友好的 Linux 源代码树中。

您需要哪一个取决于 *buffer 是用户地址还是内核地址,以及您对错误处理/检查缓冲区内容的需求有多严格(例如,是 123qx 无效还是应该返回 123 ?)。

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 ?).

谁许谁一生繁华 2024-11-17 04:33:09

最小可运行 kstrtoull_from_user debugfs 示例

kstrto*_from_user 系列在处理用户数据时非常方便。

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");

用法:

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

Dmesg 输出:

ok = 1234
ko = -22

在 Linux 内核 4.16 中测试 这个 QEMU + Buildroot设置

对于这个特定的示例,您可能想要使用 debugfs_create_u32 代替。

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.

殊姿 2024-11-17 04:33:09

由于Linux内核中没有许多常用函数/宏,因此您无法使用任何直接函数从字符串缓冲区中获取整数值。

这是我长期以来一直使用的代码,它可以用于所有 *NIX 风格(可能无需任何修改)。

这是代码的修改形式,我很久以前就在一个开源项目中使用过它(现在不记得名字了)。

#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
}

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
}
月野兔 2024-11-17 04:33:09

我使用 sscanf() (内核版本)从字符串流中进行扫描,它适用于 2.6.39-gentoo-r3。坦率地说,我永远无法让 simple_strtol() 在内核中工作——我目前正在弄清楚为什么这在我的机器上不起作用。

  ...
  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"
  ...

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"
  ...
温柔戏命师 2024-11-17 04:33:09

使用atoi和isdigit(注意isdigit只接受一个字符)。
http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文